code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __A ( __lowerCamelCase ) -> bool: a = int(number**0.5 ) return number == sq * sq def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> tuple[int, int]: a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den a = x_den * y_den * z_den a = gcd(__lowerCamelCase , __lowerCamelCase ) top //= hcf bottom //= hcf return top, bottom def __A ( __lowerCamelCase = 35 ) -> int: a = set() a = 42 a = Fraction(0 ) a = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 a = x_num * y_den + x_den * y_num a = x_den * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) a = x_den * x_den * y_den * y_den if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=-1 a = x_num * y_num a = x_den * y_num + x_num * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = x_num * x_num * y_num * y_num a = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) for num, den in unique_s: total += Fraction(__lowerCamelCase , __lowerCamelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(F'{solution() = }')
347
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer a = flax_key_tuple[:-1] + ("""weight""",) a = torch.permute(__lowerCamelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCamelCase ): # linear layer a = flax_key_tuple[:-1] + ("""weight""",) a = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: a = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: if "metadata" in layer: a = layer.split("""metadata""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: a = layer.split("""kvstore""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: a = layer.split("""/""" ) a = """/""".join(split_layer[:-1] ) a = (split_layer[-1],) if "kvstore/path" in layer: a = f'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: a = """file""" else: a = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __A ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: a = rename_keys(__lowerCamelCase ) a = {} for k, v in current_block.items(): a = v a = new_current_block torch.save(__lowerCamelCase , __lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = WEIGHTS_NAME ) -> List[str]: a = convert_file_size_to_int(__lowerCamelCase ) a = [] a = {} a = 0 a = 0 os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: a = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] a = flatten_dict(__lowerCamelCase , sep="""/""" ) a = {} for layer in checkpoint_info.keys(): a , a , a = get_key_and_tensorstore_dict( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if curr_real_layer_name in all_layers: a = content else: a = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() a = torch.tensor(__lowerCamelCase ) a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts a , a = rename_base_flax_keys(tuple(key.split("""/""" ) ) , __lowerCamelCase ) a = """/""".join(__lowerCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: a = os.path.join( __lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block a = {} a = 0 a = raw_weights.to(getattr(__lowerCamelCase , __lowerCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index a = {} a = {} for idx, shard in enumerate(__lowerCamelCase ): a = weights_name.replace( """.bin""" , f'-{idx+1:05d}-of-{len(__lowerCamelCase ):05d}.bin' ) # len(sharded_state_dicts):05d} a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{idx+1:05d}-of-???.bin' ) ) os.rename(__lowerCamelCase , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) a = shard for key in shard: a = shard_file # Add the metadata a = {"""total_size""": total_size} a = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(__lowerCamelCase , __lowerCamelCase ) , """w""" , encoding="""utf-8""" ) as f: a = json.dumps(__lowerCamelCase , indent=2 , sort_keys=__lowerCamelCase ) + """\n""" f.write(__lowerCamelCase ) return metadata, index if __name__ == "__main__": __UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __UpperCamelCase : Any = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __A ( ) -> Tuple: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer a = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) a = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) a = TaTokenizer.from_pretrained("""t5-small""" ) a = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" a = tokenizer(__lowerCamelCase , return_tensors="""pt""" ).input_ids a = model.generate(__lowerCamelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
347
1
__UpperCamelCase : str = tuple[float, float, float] __UpperCamelCase : Union[str, Any] = tuple[float, float, float] def __A ( __lowerCamelCase , __lowerCamelCase ) -> Vectorad: a = end_pointa[0] - end_pointa[0] a = end_pointa[1] - end_pointa[1] a = end_pointa[2] - end_pointa[2] return (x, y, z) def __A ( __lowerCamelCase , __lowerCamelCase ) -> Vectorad: a = ab[1] * ac[2] - ab[2] * ac[1] # *i a = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j a = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def __A ( __lowerCamelCase , __lowerCamelCase ) -> bool: return tuple(round(__lowerCamelCase , __lowerCamelCase ) for x in vector ) == (0, 0, 0) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 10 ) -> bool: a = create_vector(__lowerCamelCase , __lowerCamelCase ) a = create_vector(__lowerCamelCase , __lowerCamelCase ) return is_zero_vector(get_ad_vectors_cross(__lowerCamelCase , __lowerCamelCase ) , __lowerCamelCase )
347
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __UpperCamelCase : Union[str, Any] = (720, 1_280) # Height, Width __UpperCamelCase : Any = (0.4, 0.6) # if height or width lower than this scale, drop it. __UpperCamelCase : str = 1 / 100 __UpperCamelCase : Optional[int] = "" __UpperCamelCase : List[Any] = "" __UpperCamelCase : Union[str, Any] = "" __UpperCamelCase : Tuple = 250 def __A ( ) -> None: a , a = get_dataset(__lowerCamelCase , __lowerCamelCase ) for index in range(__lowerCamelCase ): a = random.sample(range(len(__lowerCamelCase ) ) , 4 ) a , a , a = update_image_and_anno( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , filter_scale=__lowerCamelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' a = random_chars(32 ) a = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] a = f'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(f'{file_root}.jpg' , __lowerCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) a = [] for anno in new_annos: a = anno[3] - anno[1] a = anno[4] - anno[2] a = anno[1] + width / 2 a = anno[2] + height / 2 a = f'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(__lowerCamelCase ) with open(f'{file_root}.txt' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> tuple[list, list]: a = [] a = [] for label_file in glob.glob(os.path.join(__lowerCamelCase , """*.txt""" ) ): a = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCamelCase ) as in_file: a = in_file.readlines() a = os.path.join(__lowerCamelCase , f'{label_name}.jpg' ) a = [] for obj_list in obj_lists: a = obj_list.rstrip("""\n""" ).split(""" """ ) a = float(obj[1] ) - float(obj[3] ) / 2 a = float(obj[2] ) - float(obj[4] ) / 2 a = float(obj[1] ) + float(obj[3] ) / 2 a = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__lowerCamelCase ) labels.append(__lowerCamelCase ) return img_paths, labels def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 0.0 , ) -> tuple[list, list, str]: a = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = int(scale_x * output_size[1] ) a = int(scale_y * output_size[0] ) a = [] a = [] for i, index in enumerate(__lowerCamelCase ): a = all_img_list[index] path_list.append(__lowerCamelCase ) a = all_annos[index] a = cva.imread(__lowerCamelCase ) if i == 0: # top-left a = cva.resize(__lowerCamelCase , (divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = bbox[2] * scale_y a = bbox[3] * scale_x a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right a = cva.resize(__lowerCamelCase , (output_size[1] - divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = bbox[2] * scale_y a = scale_x + bbox[3] * (1 - scale_x) a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left a = cva.resize(__lowerCamelCase , (divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = scale_y + bbox[2] * (1 - scale_y) a = bbox[3] * scale_x a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right a = cva.resize( __lowerCamelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = scale_y + bbox[2] * (1 - scale_y) a = scale_x + bbox[3] * (1 - scale_x) a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: a = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __A ( __lowerCamelCase ) -> str: assert number_char > 1, "The number of character should greater than 1" a = ascii_lowercase + digits return "".join(random.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
347
1
import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): @property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = ort.SessionOptions() a = False return options def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) a = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__magic_name__ ) a = """A red cat sitting on a park bench""" a = np.random.RandomState(0 ) a = pipe( prompt=__magic_name__ , image=__magic_name__ , mask_image=__magic_name__ , guidance_scale=7.5 , num_inference_steps=10 , generator=__magic_name__ , output_type="""np""" , ) a = output.images a = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) a = np.array([0.2514, 0.3007, 0.3517, 0.1790, 0.2382, 0.3167, 0.1944, 0.2273, 0.2464] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) a = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-inpainting""" , subfolder="""scheduler""" , revision="""onnx""" ) a = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__magic_name__ ) a = """A red cat sitting on a park bench""" a = np.random.RandomState(0 ) a = pipe( prompt=__magic_name__ , image=__magic_name__ , mask_image=__magic_name__ , guidance_scale=7.5 , num_inference_steps=20 , generator=__magic_name__ , output_type="""np""" , ) a = output.images a = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) a = np.array([0.0086, 0.0077, 0.0083, 0.0093, 0.0107, 0.0139, 0.0094, 0.0097, 0.0125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
347
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Optional[Any] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "MobileNetV2OnnxConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ["MobileNetV2FeatureExtractor"] __UpperCamelCase : Tuple = ["MobileNetV2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV2ForImageClassification", "MobileNetV2ForSemanticSegmentation", "MobileNetV2Model", "MobileNetV2PreTrainedModel", "load_tf_weights_in_mobilenet_v2", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
class __lowerCAmelCase : def __init__( self :Optional[Any] , __magic_name__ :Tuple , __magic_name__ :Optional[Any] ): '''simple docstring''' a = name a = val def __str__( self :Union[str, Any] ): '''simple docstring''' return F'{self.__class__.__name__}({self.name}, {self.val})' def __lt__( self :Any , __magic_name__ :List[Any] ): '''simple docstring''' return self.val < other.val class __lowerCAmelCase : def __init__( self :Tuple , __magic_name__ :Optional[Any] ): '''simple docstring''' a = {} a = {} a = self.build_heap(__magic_name__ ) def __getitem__( self :Tuple , __magic_name__ :Optional[int] ): '''simple docstring''' return self.get_value(__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :str ): '''simple docstring''' return (idx - 1) // 2 def lowerCamelCase__ ( self :Tuple , __magic_name__ :List[str] ): '''simple docstring''' return idx * 2 + 1 def lowerCamelCase__ ( self :Any , __magic_name__ :int ): '''simple docstring''' return idx * 2 + 2 def lowerCamelCase__ ( self :Tuple , __magic_name__ :Any ): '''simple docstring''' return self.heap_dict[key] def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Union[str, Any] ): '''simple docstring''' a = len(__magic_name__ ) - 1 a = self.get_parent_idx(__magic_name__ ) for idx, i in enumerate(__magic_name__ ): a = idx a = i.val for i in range(__magic_name__ , -1 , -1 ): self.sift_down(__magic_name__ , __magic_name__ ) return array def lowerCamelCase__ ( self :Any , __magic_name__ :Optional[int] , __magic_name__ :Optional[Any] ): '''simple docstring''' while True: a = self.get_left_child_idx(__magic_name__ ) # noqa: E741 a = self.get_right_child_idx(__magic_name__ ) a = idx if l < len(__magic_name__ ) and array[l] < array[idx]: a = l if r < len(__magic_name__ ) and array[r] < array[smallest]: a = r if smallest != idx: a , a = array[smallest], array[idx] ( ( a ) , ( a ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) a = smallest else: break def lowerCamelCase__ ( self :Dict , __magic_name__ :str ): '''simple docstring''' a = self.get_parent_idx(__magic_name__ ) while p >= 0 and self.heap[p] > self.heap[idx]: a , a = self.heap[idx], self.heap[p] a , a = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) a = p a = self.get_parent_idx(__magic_name__ ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' return self.heap[0] def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a , a = self.heap[-1], self.heap[0] a , a = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) a = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def lowerCamelCase__ ( self :str , __magic_name__ :Any ): '''simple docstring''' self.heap.append(__magic_name__ ) a = len(self.heap ) - 1 a = node.val self.sift_up(len(self.heap ) - 1 ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return len(self.heap ) == 0 def lowerCamelCase__ ( self :str , __magic_name__ :int , __magic_name__ :Any ): '''simple docstring''' assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" a = new_value a = new_value self.sift_up(self.idx_of_element[node] ) __UpperCamelCase : Optional[Any] = Node("R", -1) __UpperCamelCase : Union[str, Any] = Node("B", 6) __UpperCamelCase : List[str] = Node("A", 3) __UpperCamelCase : Union[str, Any] = Node("X", 1) __UpperCamelCase : int = Node("E", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __UpperCamelCase : List[str] = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("Min Heap - before decrease key") for i in my_min_heap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
347
def __A ( __lowerCamelCase ) -> bool: if num < 0: return False a = num a = 0 while num > 0: a = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
1
import math import unittest def __A ( __lowerCamelCase ) -> bool: assert isinstance(__lowerCamelCase , __lowerCamelCase ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__lowerCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :Any ): '''simple docstring''' self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' with self.assertRaises(__magic_name__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , """Zero doesn't have any positive factors, primes must have exactly two.""" , ) self.assertFalse( is_prime(1 ) , """One only has 1 positive factor, primes must have exactly two.""" , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
347
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = CanineTokenizer UpperCamelCase__ = False def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().setUp() a = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return CanineTokenizer.from_pretrained("""google/canine-s""" ) def lowerCamelCase__ ( self :Tuple , **__magic_name__ :Dict ): '''simple docstring''' a = self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) a = 1024 return tokenizer @require_torch def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.canine_tokenizer a = ["""Life is like a box of chocolates.""", """You never know what you're gonna get."""] # fmt: off a = [5_7344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 5_7345, 0, 0, 0, 0] # fmt: on a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) self.assertIsInstance(__magic_name__ , __magic_name__ ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = ["""Once there was a man.""", """He wrote a test in HuggingFace Tranformers."""] a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("""input_ids""" , __magic_name__ ) self.assertIn("""attention_mask""" , __magic_name__ ) self.assertIn("""token_type_ids""" , __magic_name__ ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = [ """What's the weater?""", """It's about 25 degrees.""", ] a = tokenizer( text_target=__magic_name__ , max_length=32 , padding="""max_length""" , truncation=__magic_name__ , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) shutil.rmtree(__magic_name__ ) a = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: a = chr(0Xe_0_0_7 ) additional_special_tokens.append(__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertIn(__magic_name__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) a = tokenizer.__class__.from_pretrained(__magic_name__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a , a = self.get_clean_sequence(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_5 a = chr(__magic_name__ ) tokenizer.add_special_tokens({"""cls_token""": special_token} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) a = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , input_encoded + special_token_id ) a = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertTrue(special_token not in decoded ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = chr(0Xe_0_0_5 ) a = chr(0Xe_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=__magic_name__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"""additional_special_tokens""": [SPECIAL_TOKEN_2]} ) a = tokenizer.tokenize(__magic_name__ ) a = tokenizer.tokenize(__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(token_a[0] , __magic_name__ ) self.assertEqual(token_a[0] , __magic_name__ ) @require_tokenizers def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(__magic_name__ ) tokenizer.from_pretrained(__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__magic_name__ ) with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = [new_token_a] a = [new_token_a] with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files a = tokenizer_class.from_pretrained(__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) a = 0Xe_0_0_7 a = chr(__magic_name__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained a = [AddedToken(__magic_name__ , lstrip=__magic_name__ )] a = tokenizer_class.from_pretrained( __magic_name__ , additional_special_tokens=__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = """hello world""" if self.space_between_special_tokens: a = """[CLS] hello world [SEP]""" else: a = input a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.decode(__magic_name__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(__magic_name__ , [output, output.lower()] ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = [ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] a = """a""" a = ord(__magic_name__ ) for attr in attributes_list: setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [] ) a = 0Xe_0_0_6 a = chr(__magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [additional_special_token_id] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [additional_special_token] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [additional_special_token_id] ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :str ): '''simple docstring''' pass def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass
347
1
from __future__ import annotations import math def __A ( __lowerCamelCase , __lowerCamelCase ) -> float: a = u for i in range(1 , __lowerCamelCase ): a = temp * (u - i) return temp def __A ( ) -> None: a = int(input("""enter the numbers of values: """ ) ) a = [] for _ in range(__lowerCamelCase ): y.append([] ) for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): y[i].append(__lowerCamelCase ) a = 0 print("""enter the values of parameters in a list: """ ) a = list(map(__lowerCamelCase , input().split() ) ) print("""enter the values of corresponding parameters: """ ) for i in range(__lowerCamelCase ): a = float(input() ) a = int(input("""enter the value to interpolate: """ ) ) a = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , __lowerCamelCase ): for j in range(n - i ): a = y[j + 1][i - 1] - y[j][i - 1] a = y[0][0] for i in range(1 , __lowerCamelCase ): summ += (ucal(__lowerCamelCase , __lowerCamelCase ) * y[0][i]) / math.factorial(__lowerCamelCase ) print(f'the value at {value} is {summ}' ) if __name__ == "__main__": main()
347
def __A ( __lowerCamelCase ) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
347
1
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCamelCase : Union[str, Any] = "\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"A red cartoon frog, 4k\"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n ... )\n >>> pipe.to(\"cuda\")\n\n >>> init_image = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/frog.png\"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save(\"red_frog.png\")\n ```\n" def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=8 ) -> Dict: a = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def __A ( __lowerCamelCase , __lowerCamelCase=512 , __lowerCamelCase=512 ) -> Optional[Any]: a = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) a = np.array(pil_image.convert("""RGB""" ) ) a = arr.astype(np.floataa ) / 127.5 - 1 a = np.transpose(__lowerCamelCase , [2, 0, 1] ) a = torch.from_numpy(__lowerCamelCase ).unsqueeze(0 ) return image class __lowerCAmelCase ( __magic_name__ ): def __init__( self :List[str] , __magic_name__ :UNetaDConditionModel , __magic_name__ :DDPMScheduler , __magic_name__ :VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=__magic_name__ , scheduler=__magic_name__ , movq=__magic_name__ , ) a = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Any , __magic_name__ :Tuple , __magic_name__ :List[Any] ): '''simple docstring''' a = min(int(num_inference_steps * strength ) , __magic_name__ ) a = max(num_inference_steps - init_timestep , 0 ) a = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCamelCase__ ( self :str , __magic_name__ :int , __magic_name__ :Optional[Any] , __magic_name__ :Optional[int] , __magic_name__ :int , __magic_name__ :Dict , __magic_name__ :Union[str, Any] , __magic_name__ :List[Any]=None ): '''simple docstring''' if not isinstance(__magic_name__ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__magic_name__ )}' ) a = image.to(device=__magic_name__ , dtype=__magic_name__ ) a = batch_size * num_images_per_prompt if image.shape[1] == 4: a = image else: if isinstance(__magic_name__ , __magic_name__ ) and len(__magic_name__ ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(__magic_name__ )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) elif isinstance(__magic_name__ , __magic_name__ ): a = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__magic_name__ ) ] a = torch.cat(__magic_name__ , dim=0 ) else: a = self.movq.encode(__magic_name__ ).latent_dist.sample(__magic_name__ ) a = self.movq.config.scaling_factor * init_latents a = torch.cat([init_latents] , dim=0 ) a = init_latents.shape a = randn_tensor(__magic_name__ , generator=__magic_name__ , device=__magic_name__ , dtype=__magic_name__ ) # get latents a = self.scheduler.add_noise(__magic_name__ , __magic_name__ , __magic_name__ ) a = init_latents return latents def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :str=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) a = torch.device(F'cuda:{gpu_id}' ) a = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :int , __magic_name__ :int=0 ): '''simple docstring''' if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) a = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=__magic_name__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a = None for cpu_offloaded_model in [self.unet, self.movq]: a , a = cpu_offload_with_hook(__magic_name__ , __magic_name__ , prev_module_hook=__magic_name__ ) # We'll offload the last model manually. a = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(__magic_name__ , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__magic_name__ ) def __call__( self :Any , __magic_name__ :Union[torch.FloatTensor, List[torch.FloatTensor]] , __magic_name__ :Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] , __magic_name__ :Union[torch.FloatTensor, List[torch.FloatTensor]] , __magic_name__ :int = 512 , __magic_name__ :int = 512 , __magic_name__ :int = 100 , __magic_name__ :float = 4.0 , __magic_name__ :float = 0.3 , __magic_name__ :int = 1 , __magic_name__ :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __magic_name__ :Optional[str] = "pil" , __magic_name__ :bool = True , ): '''simple docstring''' a = self._execution_device a = guidance_scale > 1.0 if isinstance(__magic_name__ , __magic_name__ ): a = torch.cat(__magic_name__ , dim=0 ) a = image_embeds.shape[0] if isinstance(__magic_name__ , __magic_name__ ): a = torch.cat(__magic_name__ , dim=0 ) if do_classifier_free_guidance: a = image_embeds.repeat_interleave(__magic_name__ , dim=0 ) a = negative_image_embeds.repeat_interleave(__magic_name__ , dim=0 ) a = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__magic_name__ ) if not isinstance(__magic_name__ , __magic_name__ ): a = [image] if not all(isinstance(__magic_name__ , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F'Input is in incorrect format: {[type(__magic_name__ ) for i in image]}. Currently, we only support PIL image and pytorch tensor' ) a = torch.cat([prepare_image(__magic_name__ , __magic_name__ , __magic_name__ ) for i in image] , dim=0 ) a = image.to(dtype=image_embeds.dtype , device=__magic_name__ ) a = self.movq.encode(__magic_name__ )["""latents"""] a = latents.repeat_interleave(__magic_name__ , dim=0 ) self.scheduler.set_timesteps(__magic_name__ , device=__magic_name__ ) a , a = self.get_timesteps(__magic_name__ , __magic_name__ , __magic_name__ ) a = timesteps[:1].repeat(batch_size * num_images_per_prompt ) a , a = downscale_height_and_width(__magic_name__ , __magic_name__ , self.movq_scale_factor ) a = self.prepare_latents( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , image_embeds.dtype , __magic_name__ , __magic_name__ ) for i, t in enumerate(self.progress_bar(__magic_name__ ) ): # expand the latents if we are doing classifier free guidance a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a = {"""image_embeds""": image_embeds} a = self.unet( sample=__magic_name__ , timestep=__magic_name__ , encoder_hidden_states=__magic_name__ , added_cond_kwargs=__magic_name__ , return_dict=__magic_name__ , )[0] if do_classifier_free_guidance: a , a = noise_pred.split(latents.shape[1] , dim=1 ) a , a = noise_pred.chunk(2 ) a , a = variance_pred.chunk(2 ) a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a , a = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a = self.scheduler.step( __magic_name__ , __magic_name__ , __magic_name__ , generator=__magic_name__ , )[0] # post-processing a = self.movq.decode(__magic_name__ , force_not_quantize=__magic_name__ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a = image * 0.5 + 0.5 a = image.clamp(0 , 1 ) a = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a = self.numpy_to_pil(__magic_name__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=__magic_name__ )
347
def __A ( __lowerCamelCase ) -> int: if not numbers: return 0 if not isinstance(__lowerCamelCase , (list, tuple) ) or not all( isinstance(__lowerCamelCase , __lowerCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) a = a = a = numbers[0] for i in range(1 , len(__lowerCamelCase ) ): # update the maximum and minimum subarray products a = numbers[i] if number < 0: a , a = min_till_now, max_till_now a = max(__lowerCamelCase , max_till_now * number ) a = min(__lowerCamelCase , min_till_now * number ) # update the maximum product found till now a = max(__lowerCamelCase , __lowerCamelCase ) return max_prod
347
1
import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __lowerCAmelCase : @staticmethod def lowerCamelCase__ ( *__magic_name__ :Tuple , **__magic_name__ :str ): '''simple docstring''' pass @is_pipeline_test @require_vision class __lowerCAmelCase ( unittest.TestCase ): @require_torch def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , ) a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) a = image_classifier(__magic_name__ , candidate_labels=["""a""", """b""", """c"""] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__magic_name__ ) , [ [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}], [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """c"""}, {"""score""": 0.333, """label""": """b"""}], ] , ) a = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(__magic_name__ ) , [ [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], ] , ) @require_tf def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , framework="""tf""" ) a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) a = image_classifier(__magic_name__ , candidate_labels=["""a""", """b""", """c"""] ) self.assertEqual( nested_simplify(__magic_name__ ) , [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}] , ) a = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(__magic_name__ ) , [ [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], [ {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, {"""score""": 0.333, """label""": ANY(__magic_name__ )}, ], ] , ) @slow @require_torch def lowerCamelCase__ ( self :str ): '''simple docstring''' a = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , ) # This is an image of 2 cats with remotes and no planes a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) a = image_classifier(__magic_name__ , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(__magic_name__ ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) a = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(__magic_name__ ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , ) @slow @require_tf def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , framework="""tf""" ) # This is an image of 2 cats with remotes and no planes a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) a = image_classifier(__magic_name__ , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(__magic_name__ ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) a = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(__magic_name__ ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , )
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCamelCase : Optional[Any] = { "configuration_wav2vec2": ["WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2Config"], "feature_extraction_wav2vec2": ["Wav2Vec2FeatureExtractor"], "processing_wav2vec2": ["Wav2Vec2Processor"], "tokenization_wav2vec2": ["Wav2Vec2CTCTokenizer", "Wav2Vec2Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = [ "WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ForAudioFrameClassification", "Wav2Vec2ForCTC", "Wav2Vec2ForMaskedLM", "Wav2Vec2ForPreTraining", "Wav2Vec2ForSequenceClassification", "Wav2Vec2ForXVector", "Wav2Vec2Model", "Wav2Vec2PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ "TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWav2Vec2ForCTC", "TFWav2Vec2Model", "TFWav2Vec2PreTrainedModel", "TFWav2Vec2ForSequenceClassification", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "FlaxWav2Vec2ForCTC", "FlaxWav2Vec2ForPreTraining", "FlaxWav2Vec2Model", "FlaxWav2Vec2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class __lowerCAmelCase ( unittest.TestCase ): UpperCamelCase__ = StableDiffusionLDMaDPipeline UpperCamelCase__ = TEXT_TO_IMAGE_PARAMS UpperCamelCase__ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase__ = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase__ ( self :str ): '''simple docstring''' torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) a = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__magic_name__ , set_alpha_to_one=__magic_name__ , ) torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) a = CLIPTextModel(__magic_name__ ) a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) a = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowerCamelCase__ ( self :List[str] , __magic_name__ :int , __magic_name__ :Dict=0 ): '''simple docstring''' if str(__magic_name__ ).startswith("""mps""" ): a = torch.manual_seed(__magic_name__ ) else: a = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) a = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def lowerCamelCase__ ( self :int ): '''simple docstring''' a = """cpu""" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionLDMaDPipeline(**__magic_name__ ) a = ldmad_pipe.to(__magic_name__ ) ldmad_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_dummy_inputs(__magic_name__ ) a = ldmad_pipe(**__magic_name__ ) a , a = output.rgb, output.depth a = rgb[0, -3:, -3:, -1] a = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) a = np.array( [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262] ) a = np.array([103.46727, 85.812004, 87.849236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1E-2 def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.get_dummy_components() a = StableDiffusionLDMaDPipeline(**__magic_name__ ) a = ldmad_pipe.to(__magic_name__ ) ldmad_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_dummy_inputs(__magic_name__ ) a = 3 * [inputs["""prompt"""]] # forward a = ldmad_pipe(**__magic_name__ ) a , a = output.rgb, output.depth a = rgb_slice_a[0, -3:, -3:, -1] a = depth_slice_a[0, -3:, -1] a = self.get_dummy_inputs(__magic_name__ ) a = 3 * [inputs.pop("""prompt""" )] a = ldmad_pipe.tokenizer( __magic_name__ , padding="""max_length""" , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=__magic_name__ , return_tensors="""pt""" , ) a = text_inputs["""input_ids"""].to(__magic_name__ ) a = ldmad_pipe.text_encoder(__magic_name__ )[0] a = prompt_embeds # forward a = ldmad_pipe(**__magic_name__ ) a , a = output.rgb, output.depth a = rgb_slice_a[0, -3:, -3:, -1] a = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1E-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1E-4 def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = """cpu""" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = PNDMScheduler(skip_prk_steps=__magic_name__ ) a = StableDiffusionLDMaDPipeline(**__magic_name__ ) a = ldmad_pipe.to(__magic_name__ ) ldmad_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_dummy_inputs(__magic_name__ ) a = """french fries""" a = ldmad_pipe(**__magic_name__ , negative_prompt=__magic_name__ ) a , a = output.rgb, output.depth a = rgb[0, -3:, -3:, -1] a = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) a = np.array( [0.37044, 0.71811503, 0.7223251, 0.48603675, 0.5638391, 0.6364948, 0.42833704, 0.4901315, 0.47926217] ) a = np.array([107.84738, 84.62802, 89.962135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1E-2 @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :List[Any]="cpu" , __magic_name__ :Optional[int]=torch.floataa , __magic_name__ :int=0 ): '''simple docstring''' a = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) a = np.random.RandomState(__magic_name__ ).standard_normal((1, 4, 64, 64) ) a = torch.from_numpy(__magic_name__ ).to(device=__magic_name__ , dtype=__magic_name__ ) a = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d""" ) a = ldmad_pipe.to(__magic_name__ ) ldmad_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_inputs(__magic_name__ ) a = ldmad_pipe(**__magic_name__ ) a , a = output.rgb, output.depth a = rgb[0, -3:, -3:, -1].flatten() a = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) a = np.array( [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706] ) a = np.array( [0.9263781, 0.6678672, 0.5486515, 0.92202145, 0.67831135, 0.56253487, 0.9241694, 0.7551478, 0.6459706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3E-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3E-3 @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :int ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :str , __magic_name__ :List[str]="cpu" , __magic_name__ :Optional[int]=torch.floataa , __magic_name__ :List[str]=0 ): '''simple docstring''' a = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) a = np.random.RandomState(__magic_name__ ).standard_normal((1, 4, 64, 64) ) a = torch.from_numpy(__magic_name__ ).to(device=__magic_name__ , dtype=__magic_name__ ) a = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d""" ).to(__magic_name__ ) ldmad_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_inputs(__magic_name__ ) a = ldmad_pipe(**__magic_name__ ) a , a = output.rgb, output.depth a = 0.495586 a = 0.33795515 a = 112.48518 a = 98.489746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3 def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d-4c""" ).to(__magic_name__ ) ldmad_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_inputs(__magic_name__ ) a = ldmad_pipe(**__magic_name__ ) a , a = output.rgb, output.depth a = 0.4194127 a = 0.35375586 a = 0.5638502 a = 0.34686103 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3
347
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCamelCase ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(__lowerCamelCase ) assert result == expected
347
1
def __A ( __lowerCamelCase ) -> float: if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) a = sum(__lowerCamelCase ) / len(__lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
347
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __A ( __lowerCamelCase ) -> bool: a = int(number**0.5 ) return number == sq * sq def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> tuple[int, int]: a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den a = x_den * y_den * z_den a = gcd(__lowerCamelCase , __lowerCamelCase ) top //= hcf bottom //= hcf return top, bottom def __A ( __lowerCamelCase = 35 ) -> int: a = set() a = 42 a = Fraction(0 ) a = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 a = x_num * y_den + x_den * y_num a = x_den * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) a = x_den * x_den * y_den * y_den if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=-1 a = x_num * y_num a = x_den * y_num + x_num * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = x_num * x_num * y_num * y_num a = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) for num, den in unique_s: total += Fraction(__lowerCamelCase , __lowerCamelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(F'{solution() = }')
347
1
__UpperCamelCase : dict[str, float] = { "km/h": 1.0, "m/s": 3.6, "mph": 1.60_93_44, "knot": 1.8_52, } __UpperCamelCase : dict[str, float] = { "km/h": 1.0, "m/s": 0.2_77_77_77_78, "mph": 0.6_21_37_11_92, "knot": 0.5_39_95_68_03, } def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> float: if unit_to not in speed_chart or unit_from not in speed_chart_inverse: a = ( f'Incorrect \'from_type\' or \'to_type\' value: {unit_from!r}, {unit_to!r}\n' f'Valid values are: {", ".join(__lowerCamelCase )}' ) raise ValueError(__lowerCamelCase ) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to] , 3 ) if __name__ == "__main__": import doctest doctest.testmod()
347
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :List[str] , __magic_name__ :List[str] , __magic_name__ :List[Any]=13 , __magic_name__ :Any=7 , __magic_name__ :Optional[int]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :Any=99 , __magic_name__ :List[str]=32 , __magic_name__ :List[str]=5 , __magic_name__ :str=4 , __magic_name__ :str=37 , __magic_name__ :Optional[int]="gelu" , __magic_name__ :int=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Tuple=16 , __magic_name__ :Tuple=2 , __magic_name__ :List[str]=0.02 , __magic_name__ :Any=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = FlaxRoFormerModelTester(self ) @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) a = jnp.array([[0, 1, 2, 3, 4, 5]] ) a = model(__magic_name__ )[0] a = 5_0000 a = (1, 6, vocab_size) self.assertEqual(output.shape , __magic_name__ ) a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(__magic_name__ ) , '''Tatoeba directory does not exist.''' ) class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = tempfile.mkdtemp() return TatoebaConverter(save_dir=__magic_name__ ) @slow def lowerCamelCase__ ( self :int ): '''simple docstring''' self.resolver.convert_models(["""heb-eng"""] ) @slow def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a , a = self.resolver.write_model_card("""opus-mt-he-en""" , dry_run=__magic_name__ ) assert mmeta["long_pair"] == "heb-eng"
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __UpperCamelCase : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = XLMRobertaTokenizer UpperCamelCase__ = XLMRobertaTokenizerFast UpperCamelCase__ = True UpperCamelCase__ = True def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing a = XLMRobertaTokenizer(__magic_name__ , keep_accents=__magic_name__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = """<pad>""" a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(__magic_name__ ) , 1002 ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1002 ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = XLMRobertaTokenizer(__magic_name__ , keep_accents=__magic_name__ ) a = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__magic_name__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) a = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __magic_name__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) a = tokenizer.convert_tokens_to_ids(__magic_name__ ) self.assertListEqual( __magic_name__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) a = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def lowerCamelCase__ ( self :str ): '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return a = (self.rust_tokenizer_class, """hf-internal-testing/tiny-xlm-roberta""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): a = self.rust_tokenizer_class.from_pretrained(__magic_name__ , **__magic_name__ ) a = self.tokenizer_class.from_pretrained(__magic_name__ , **__magic_name__ ) a = tempfile.mkdtemp() a = tokenizer_r.save_pretrained(__magic_name__ ) a = tokenizer_p.save_pretrained(__magic_name__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) a = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__magic_name__ , __magic_name__ ) # Checks everything loads correctly in the same way a = tokenizer_r.from_pretrained(__magic_name__ ) a = tokenizer_p.from_pretrained(__magic_name__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__magic_name__ , __magic_name__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__magic_name__ ) # Save tokenizer rust, legacy_format=True a = tempfile.mkdtemp() a = tokenizer_r.save_pretrained(__magic_name__ , legacy_format=__magic_name__ ) a = tokenizer_p.save_pretrained(__magic_name__ ) # Checks it save with the same files self.assertSequenceEqual(__magic_name__ , __magic_name__ ) # Checks everything loads correctly in the same way a = tokenizer_r.from_pretrained(__magic_name__ ) a = tokenizer_p.from_pretrained(__magic_name__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__magic_name__ , __magic_name__ ) ) shutil.rmtree(__magic_name__ ) # Save tokenizer rust, legacy_format=False a = tempfile.mkdtemp() a = tokenizer_r.save_pretrained(__magic_name__ , legacy_format=__magic_name__ ) a = tokenizer_p.save_pretrained(__magic_name__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way a = tokenizer_r.from_pretrained(__magic_name__ ) a = tokenizer_p.from_pretrained(__magic_name__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__magic_name__ , __magic_name__ ) ) shutil.rmtree(__magic_name__ ) @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return XLMRobertaTokenizer.from_pretrained("""xlm-roberta-base""" ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__magic_name__ , f.name ) a = XLMRobertaTokenizer(f.name , keep_accents=__magic_name__ ) a = pickle.dumps(__magic_name__ ) pickle.loads(__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' if not self.test_rust_tokenizer: return a = self.get_tokenizer() a = self.get_rust_tokenizer() a = """I was born in 92000, and this is falsé.""" a = tokenizer.tokenize(__magic_name__ ) a = rust_tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = rust_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) a = self.get_rust_tokenizer() a = tokenizer.encode(__magic_name__ ) a = rust_tokenizer.encode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = """Hello World!""" a = [0, 3_5378, 6661, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(__magic_name__ , self.big_tokenizer.encode(__magic_name__ ) ) @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) a = [ 0, 3293, 83, 10, 4552, 4989, 7986, 678, 10, 5915, 111, 17_9459, 12_4850, 4, 6044, 237, 12, 6, 5, 6, 4, 6780, 705, 15, 1388, 44, 378, 1_0114, 711, 152, 20, 6, 5, 2_2376, 642, 1221, 1_5190, 3_4153, 450, 5608, 959, 1119, 5_7702, 136, 186, 47, 1098, 2_9367, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 6044, 237, 6284, 5_0901, 528, 31, 90, 34, 927, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(__magic_name__ , self.big_tokenizer.encode(__magic_name__ ) ) @slow def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = {"""input_ids""": [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name="""xlm-roberta-base""" , revision="""d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3""" , )
347
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = (IPNDMScheduler,) UpperCamelCase__ = (('''num_inference_steps''', 50),) def lowerCamelCase__ ( self :Any , **__magic_name__ :Optional[Any] ): '''simple docstring''' a = {"""num_train_timesteps""": 1000} config.update(**__magic_name__ ) return config def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple=0 , **__magic_name__ :Optional[int] ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] , __magic_name__ :List[Any]=0 , **__magic_name__ :Any ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals (must be after setting timesteps) a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) # copy over dummy past residuals new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residual (must be after setting timesteps) a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Optional[Any] , **__magic_name__ :Optional[int] ): '''simple docstring''' a = self.scheduler_classes[0] a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) a = 10 a = self.dummy_model() a = self.dummy_sample_deter scheduler.set_timesteps(__magic_name__ ) for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample return sample def lowerCamelCase__ ( self :str ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) a = self.dummy_sample a = 0.1 * sample if num_inference_steps is not None and hasattr(__magic_name__ , """set_timesteps""" ): scheduler.set_timesteps(__magic_name__ ) elif num_inference_steps is not None and not hasattr(__magic_name__ , """set_timesteps""" ): a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] a = dummy_past_residuals[:] a = scheduler.timesteps[5] a = scheduler.timesteps[6] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.full_loop() a = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_mean.item() - 254_0529 ) < 10
347
1
import math def __A ( __lowerCamelCase ) -> str: a = 0 a = 0 while num > 0: a = num % 8 a = octal + (remainder * math.floor(math.pow(10 , __lowerCamelCase ) )) counter += 1 a = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f'0o{int(__lowerCamelCase )}' def __A ( ) -> None: print("""\n2 in octal is:""" ) print(decimal_to_octal(2 ) ) # = 2 print("""\n8 in octal is:""" ) print(decimal_to_octal(8 ) ) # = 10 print("""\n65 in octal is:""" ) print(decimal_to_octal(65 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(216 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(512 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
347
__UpperCamelCase : Dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __A ( ) -> None: a = input("""Enter message: """ ) a = input("""Enter key [alphanumeric]: """ ) a = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): a = """encrypt""" a = encrypt_message(__lowerCamelCase , __lowerCamelCase ) elif mode.lower().startswith("""d""" ): a = """decrypt""" a = decrypt_message(__lowerCamelCase , __lowerCamelCase ) print(f'\n{mode.title()}ed message:' ) print(__lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """encrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """decrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: a = [] a = 0 a = key.upper() for symbol in message: a = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__lowerCamelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__lowerCamelCase ): a = 0 else: translated.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) if __name__ == "__main__": main()
347
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :Optional[Any] , __magic_name__ :Union[str, Any] , __magic_name__ :Any=7 , __magic_name__ :Optional[int]=3 , __magic_name__ :Optional[int]=30 , __magic_name__ :Tuple=400 , __magic_name__ :Dict=True , __magic_name__ :Optional[Any]=None , __magic_name__ :Tuple=True , __magic_name__ :Dict=[0.5, 0.5, 0.5] , __magic_name__ :Union[str, Any]=[0.5, 0.5, 0.5] , __magic_name__ :int=True , __magic_name__ :Dict=1 / 255 , __magic_name__ :List[str]=True , ): '''simple docstring''' a = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333} a = parent a = batch_size a = num_channels a = min_resolution a = max_resolution a = do_resize a = size a = do_normalize a = image_mean a = image_std a = do_rescale a = rescale_factor a = do_pad def lowerCamelCase__ ( self :Any ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowerCamelCase__ ( self :int , __magic_name__ :Any , __magic_name__ :int=False ): '''simple docstring''' if not batched: a = image_inputs[0] if isinstance(__magic_name__ , Image.Image ): a , a = image.size else: a , a = image.shape[1], image.shape[2] if w < h: a = int(self.size["""shortest_edge"""] * h / w ) a = self.size["""shortest_edge"""] elif w > h: a = self.size["""shortest_edge"""] a = int(self.size["""shortest_edge"""] * w / h ) else: a = self.size["""shortest_edge"""] a = self.size["""shortest_edge"""] else: a = [] for image in image_inputs: a , a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) a = max(__magic_name__ , key=lambda __magic_name__ : item[0] )[0] a = max(__magic_name__ , key=lambda __magic_name__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = ConditionalDetrImageProcessor if is_vision_available() else None def lowerCamelCase__ ( self :int ): '''simple docstring''' a = ConditionalDetrImageProcessingTester(self ) @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , """image_mean""" ) ) self.assertTrue(hasattr(__magic_name__ , """image_std""" ) ) self.assertTrue(hasattr(__magic_name__ , """do_normalize""" ) ) self.assertTrue(hasattr(__magic_name__ , """do_resize""" ) ) self.assertTrue(hasattr(__magic_name__ , """size""" ) ) def lowerCamelCase__ ( self :str ): '''simple docstring''' a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 1333} ) self.assertEqual(image_processor.do_pad , __magic_name__ ) a = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__magic_name__ ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42, """longest_edge""": 84} ) self.assertEqual(image_processor.do_pad , __magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values a , a = self.image_processor_tester.get_expected_values(__magic_name__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a , a = self.image_processor_tester.get_expected_values(__magic_name__ , batched=__magic_name__ ) a = image_processing(__magic_name__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values a , a = self.image_processor_tester.get_expected_values(__magic_name__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a = image_processing(__magic_name__ , return_tensors="""pt""" ).pixel_values a , a = self.image_processor_tester.get_expected_values(__magic_name__ , batched=__magic_name__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values a , a = self.image_processor_tester.get_expected_values(__magic_name__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a = image_processing(__magic_name__ , return_tensors="""pt""" ).pixel_values a , a = self.image_processor_tester.get_expected_values(__magic_name__ , batched=__magic_name__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: a = json.loads(f.read() ) a = {"""image_id""": 3_9769, """annotations""": target} # encode them a = ConditionalDetrImageProcessor.from_pretrained("""microsoft/conditional-detr-resnet-50""" ) a = image_processing(images=__magic_name__ , annotations=__magic_name__ , return_tensors="""pt""" ) # verify pixel values a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , __magic_name__ ) a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __magic_name__ , atol=1E-4 ) ) # verify area a = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __magic_name__ ) ) # verify boxes a = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __magic_name__ ) a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __magic_name__ , atol=1E-3 ) ) # verify image_id a = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __magic_name__ ) ) # verify is_crowd a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __magic_name__ ) ) # verify class_labels a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __magic_name__ ) ) # verify orig_size a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __magic_name__ ) ) # verify size a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __magic_name__ ) ) @slow def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: a = json.loads(f.read() ) a = {"""file_name""": """000000039769.png""", """image_id""": 3_9769, """segments_info""": target} a = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them a = ConditionalDetrImageProcessor(format="""coco_panoptic""" ) a = image_processing(images=__magic_name__ , annotations=__magic_name__ , masks_path=__magic_name__ , return_tensors="""pt""" ) # verify pixel values a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , __magic_name__ ) a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __magic_name__ , atol=1E-4 ) ) # verify area a = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __magic_name__ ) ) # verify boxes a = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __magic_name__ ) a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __magic_name__ , atol=1E-3 ) ) # verify image_id a = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __magic_name__ ) ) # verify is_crowd a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __magic_name__ ) ) # verify class_labels a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __magic_name__ ) ) # verify masks a = 82_2873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , __magic_name__ ) # verify orig_size a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __magic_name__ ) ) # verify size a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __magic_name__ ) )
347
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Tuple=13 , __magic_name__ :List[Any]=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :List[str]=True , __magic_name__ :str=99 , __magic_name__ :Optional[Any]=32 , __magic_name__ :Union[str, Any]=5 , __magic_name__ :Any=4 , __magic_name__ :int=37 , __magic_name__ :Tuple="gelu" , __magic_name__ :List[str]=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :Tuple=512 , __magic_name__ :Dict=16 , __magic_name__ :Optional[int]=2 , __magic_name__ :Optional[int]=0.02 , __magic_name__ :Optional[Any]=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :int ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = True a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = FlaxRobertaModelTester(self ) @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""roberta-base""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ )
347
1
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Optional[int] = logging.get_logger(__name__) __UpperCamelCase : Tuple = { "huggingface/autoformer-tourism-monthly": "https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json", } class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''autoformer''' UpperCamelCase__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self :int , __magic_name__ :Optional[int] = None , __magic_name__ :Optional[int] = None , __magic_name__ :str = "student_t" , __magic_name__ :str = "nll" , __magic_name__ :int = 1 , __magic_name__ :List[int] = [1, 2, 3, 4, 5, 6, 7] , __magic_name__ :bool = True , __magic_name__ :int = 0 , __magic_name__ :int = 0 , __magic_name__ :int = 0 , __magic_name__ :int = 0 , __magic_name__ :Optional[List[int]] = None , __magic_name__ :Optional[List[int]] = None , __magic_name__ :int = 64 , __magic_name__ :int = 2 , __magic_name__ :int = 2 , __magic_name__ :int = 2 , __magic_name__ :int = 2 , __magic_name__ :int = 32 , __magic_name__ :int = 32 , __magic_name__ :str = "gelu" , __magic_name__ :float = 0.1 , __magic_name__ :float = 0.1 , __magic_name__ :float = 0.1 , __magic_name__ :float = 0.1 , __magic_name__ :float = 0.1 , __magic_name__ :int = 100 , __magic_name__ :float = 0.02 , __magic_name__ :bool = True , __magic_name__ :str=True , __magic_name__ :int = 10 , __magic_name__ :int = 25 , __magic_name__ :int = 3 , **__magic_name__ :Tuple , ): '''simple docstring''' a = prediction_length a = context_length if context_length is not None else prediction_length a = distribution_output a = loss a = input_size a = num_time_features a = lags_sequence a = scaling a = num_dynamic_real_features a = num_static_real_features a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__magic_name__ ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) a = cardinality else: a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__magic_name__ ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) a = embedding_dimension else: a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] a = num_parallel_samples # Transformer architecture configuration a = input_size * len(self.lags_sequence ) + self._number_of_features a = d_model a = encoder_attention_heads a = decoder_attention_heads a = encoder_ffn_dim a = decoder_ffn_dim a = encoder_layers a = decoder_layers a = dropout a = attention_dropout a = activation_dropout a = encoder_layerdrop a = decoder_layerdrop a = activation_function a = init_std a = use_cache # Autoformer a = label_length a = moving_average a = autocorrelation_factor super().__init__(is_encoder_decoder=__magic_name__ , **__magic_name__ ) @property def lowerCamelCase__ ( self :int ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
347
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __UpperCamelCase : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): UpperCamelCase__ = None UpperCamelCase__ = "utf-8" UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = True # deprecated UpperCamelCase__ = None # deprecated UpperCamelCase__ = 10 << 20 # 10MB UpperCamelCase__ = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): UpperCamelCase__ = JsonConfig def lowerCamelCase__ ( self :str ): '''simple docstring''' if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) a = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__magic_name__ , (str, list, tuple) ): a = data_files if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] a = [] for split_name, files in data_files.items(): if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] splits.append(datasets.SplitGenerator(name=__magic_name__ , gen_kwargs={"""files""": files} ) ) return splits def lowerCamelCase__ ( self :List[str] , __magic_name__ :pa.Table ): '''simple docstring''' if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): a = self.config.features.arrow_schema.field(__magic_name__ ).type a = pa_table.append_column(__magic_name__ , pa.array([None] * len(__magic_name__ ) , type=__magic_name__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example a = table_cast(__magic_name__ , self.config.features.arrow_schema ) return pa_table def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Union[str, Any] ): '''simple docstring''' for file_idx, file in enumerate(itertools.chain.from_iterable(__magic_name__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) # We keep only the field we are interested in a = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__magic_name__ , (list, tuple) ): a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} else: a = dataset a = pa.Table.from_pydict(__magic_name__ ) yield file_idx, self._cast_table(__magic_name__ ) # If the file has one json object per line else: with open(__magic_name__ , """rb""" ) as f: a = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small a = max(self.config.chunksize // 32 , 16 << 10 ) a = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: a = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__magic_name__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": a = batch.decode(self.config.encoding , errors=__magic_name__ ).encode("""utf-8""" ) try: while True: try: a = paj.read_json( io.BytesIO(__magic_name__ ) , read_options=paj.ReadOptions(block_size=__magic_name__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__magic_name__ , pa.ArrowInvalid ) and "straddling" not in str(__magic_name__ ) or block_size > len(__magic_name__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F'Batch of {len(__magic_name__ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( __magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) except json.JSONDecodeError: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__magic_name__ , __magic_name__ ): # list is the only sequence type supported in JSON try: a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} a = pa.Table.from_pydict(__magic_name__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError(F'Not able to read records in the JSON file at {file}.' ) from None yield file_idx, self._cast_table(__magic_name__ ) break else: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError( F'Not able to read records in the JSON file at {file}. ' F'You should probably indicate the field of the JSON file containing your records. ' F'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ' F'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__magic_name__ ) batch_idx += 1
347
1
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __lowerCAmelCase : def __init__( self :Optional[int] , __magic_name__ :str , __magic_name__ :int=2 , __magic_name__ :List[str]=3 , __magic_name__ :Optional[int]=4 , __magic_name__ :str=2 , __magic_name__ :Any=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Dict=True , __magic_name__ :List[Any]=99 , __magic_name__ :Dict=36 , __magic_name__ :Optional[Any]=3 , __magic_name__ :str=4 , __magic_name__ :Optional[Any]=37 , __magic_name__ :Dict="gelu" , __magic_name__ :Any=0.1 , __magic_name__ :Union[str, Any]=0.1 , __magic_name__ :Dict=512 , __magic_name__ :str=16 , __magic_name__ :List[Any]=2 , __magic_name__ :Tuple=0.02 , __magic_name__ :Any=6 , __magic_name__ :Optional[int]=6 , __magic_name__ :Tuple=3 , __magic_name__ :str=4 , __magic_name__ :List[str]=None , __magic_name__ :str=1000 , ): '''simple docstring''' a = parent a = batch_size a = num_channels a = image_size a = patch_size a = text_seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = coordinate_size a = shape_size a = num_labels a = num_choices a = scope a = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) a = text_seq_length a = (image_size // patch_size) ** 2 + 1 a = self.text_seq_length + self.image_seq_length def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) a = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a = bbox[i, j, 3] a = bbox[i, j, 1] a = t if bbox[i, j, 2] < bbox[i, j, 0]: a = bbox[i, j, 2] a = bbox[i, j, 0] a = t a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.text_seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) a = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def lowerCamelCase__ ( self :int , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :List[str] , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int ): '''simple docstring''' a = LayoutLMvaModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # text + image a = model(__magic_name__ , pixel_values=__magic_name__ ) a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only a = model(__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only a = model(pixel_values=__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :List[Any] , __magic_name__ :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Union[str, Any] , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :List[str] , __magic_name__ :List[str] ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Dict , __magic_name__ :Optional[Any] , __magic_name__ :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :int , __magic_name__ :List[str] , __magic_name__ :Tuple ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :str , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :str , __magic_name__ :List[str] , __magic_name__ :Optional[int] , __magic_name__ :Optional[Any] ): '''simple docstring''' a = LayoutLMvaForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase__ = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :Optional[Any] , __magic_name__ :List[str] , __magic_name__ :List[Any] ): '''simple docstring''' return True def lowerCamelCase__ ( self :int ): '''simple docstring''' a = LayoutLMvaModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :Any=False ): '''simple docstring''' a = copy.deepcopy(__magic_name__ ) if model_class in get_values(__magic_name__ ): a = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__magic_name__ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__magic_name__ ): a = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in get_values(__magic_name__ ): a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__magic_name__ , ) return inputs_dict def lowerCamelCase__ ( self :str ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a = type self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def lowerCamelCase__ ( self :int ): '''simple docstring''' for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = LayoutLMvaModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def __A ( ) -> str: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__magic_name__ ) if is_vision_available() else None @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(__magic_name__ ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__magic_name__ , return_tensors="""pt""" ).pixel_values.to(__magic_name__ ) a = torch.tensor([[1, 2]] ) a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass a = model( input_ids=input_ids.to(__magic_name__ ) , bbox=bbox.to(__magic_name__ ) , pixel_values=pixel_values.to(__magic_name__ ) , ) # verify the logits a = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __magic_name__ ) a = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :List[str] , __magic_name__ :int="</s>" , __magic_name__ :List[Any]="<unk>" , __magic_name__ :Optional[Any]="<pad>" , __magic_name__ :Optional[int]=125 , __magic_name__ :List[str]=None , **__magic_name__ :List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: a = [F'<extra_id_{i}>' for i in range(__magic_name__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens a = len(set(filter(lambda __magic_name__ : bool("""extra_id""" in str(__magic_name__ ) ) , __magic_name__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to ByT5Tokenizer. In this case the additional_special_tokens must include the""" """ extra_ids tokens""" ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token super().__init__( eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , extra_ids=__magic_name__ , additional_special_tokens=__magic_name__ , **__magic_name__ , ) a = extra_ids a = 2**8 # utf is 8 bits # define special tokens dict a = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } a = len(self.special_tokens_encoder ) a = len(__magic_name__ ) for i, token in enumerate(__magic_name__ ): a = self.vocab_size + i - n a = {v: k for k, v in self.special_tokens_encoder.items()} @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def lowerCamelCase__ ( self :Any , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None , __magic_name__ :bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__magic_name__ )) + [1] return ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def lowerCamelCase__ ( self :str , __magic_name__ :List[int] ): '''simple docstring''' if len(__magic_name__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = self._add_eos_if_not_present(__magic_name__ ) if token_ids_a is None: return token_ids_a else: a = self._add_eos_if_not_present(__magic_name__ ) return token_ids_a + token_ids_a def lowerCamelCase__ ( self :List[str] , __magic_name__ :str ): '''simple docstring''' a = [chr(__magic_name__ ) for i in text.encode("""utf-8""" )] return tokens def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if token in self.special_tokens_encoder: a = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: a = self.added_tokens_encoder[token] elif len(__magic_name__ ) != 1: a = self.unk_token_id else: a = ord(__magic_name__ ) + self._num_special_tokens return token_id def lowerCamelCase__ ( self :List[str] , __magic_name__ :Dict ): '''simple docstring''' if index in self.special_tokens_decoder: a = self.special_tokens_decoder[index] else: a = chr(index - self._num_special_tokens ) return token def lowerCamelCase__ ( self :Tuple , __magic_name__ :Optional[int] ): '''simple docstring''' a = b"""""" for token in tokens: if token in self.special_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.added_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.special_tokens_encoder: a = token.encode("""utf-8""" ) elif token in self.added_tokens_encoder: a = token.encode("""utf-8""" ) else: a = bytes([ord(__magic_name__ )] ) bstring += tok_string a = bstring.decode("""utf-8""" , errors="""ignore""" ) return string def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :str , __magic_name__ :Optional[str] = None ): '''simple docstring''' return ()
347
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Any = { "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json", } class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''layoutlmv3''' def __init__( self :int , __magic_name__ :Optional[int]=5_0265 , __magic_name__ :Dict=768 , __magic_name__ :Optional[Any]=12 , __magic_name__ :Union[str, Any]=12 , __magic_name__ :Tuple=3072 , __magic_name__ :Tuple="gelu" , __magic_name__ :Union[str, Any]=0.1 , __magic_name__ :Optional[Any]=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Tuple=2 , __magic_name__ :Optional[int]=0.02 , __magic_name__ :Optional[int]=1E-5 , __magic_name__ :Tuple=1 , __magic_name__ :Optional[int]=0 , __magic_name__ :List[str]=2 , __magic_name__ :int=1024 , __magic_name__ :Optional[Any]=128 , __magic_name__ :List[Any]=128 , __magic_name__ :str=True , __magic_name__ :int=32 , __magic_name__ :str=128 , __magic_name__ :Tuple=64 , __magic_name__ :Optional[Any]=256 , __magic_name__ :Optional[int]=True , __magic_name__ :List[str]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :List[Any]=224 , __magic_name__ :Any=3 , __magic_name__ :Optional[int]=16 , __magic_name__ :str=None , **__magic_name__ :Optional[int] , ): '''simple docstring''' super().__init__( vocab_size=__magic_name__ , hidden_size=__magic_name__ , num_hidden_layers=__magic_name__ , num_attention_heads=__magic_name__ , intermediate_size=__magic_name__ , hidden_act=__magic_name__ , hidden_dropout_prob=__magic_name__ , attention_probs_dropout_prob=__magic_name__ , max_position_embeddings=__magic_name__ , type_vocab_size=__magic_name__ , initializer_range=__magic_name__ , layer_norm_eps=__magic_name__ , pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ , ) a = max_ad_position_embeddings a = coordinate_size a = shape_size a = has_relative_attention_bias a = rel_pos_bins a = max_rel_pos a = has_spatial_attention_bias a = rel_ad_pos_bins a = max_rel_ad_pos a = text_embed a = visual_embed a = input_size a = num_channels a = patch_size a = classifier_dropout class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = version.parse('''1.12''' ) @property def lowerCamelCase__ ( self :str ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' return 1E-5 @property def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' return 12 def lowerCamelCase__ ( self :str , __magic_name__ :"ProcessorMixin" , __magic_name__ :int = -1 , __magic_name__ :int = -1 , __magic_name__ :bool = False , __magic_name__ :Optional["TensorType"] = None , __magic_name__ :int = 3 , __magic_name__ :int = 40 , __magic_name__ :int = 40 , ): '''simple docstring''' setattr(processor.image_processor , """apply_ocr""" , __magic_name__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX a = compute_effective_axis_dimension( __magic_name__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX a = processor.tokenizer.num_special_tokens_to_add(__magic_name__ ) a = compute_effective_axis_dimension( __magic_name__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__magic_name__ ) # Generate dummy inputs according to compute batch and sequence a = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes a = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) a = self._generate_dummy_images(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) a = dict( processor( __magic_name__ , text=__magic_name__ , boxes=__magic_name__ , return_tensors=__magic_name__ , ) ) return inputs
347
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __lowerCAmelCase : def __init__( self :Optional[int] , __magic_name__ :str , __magic_name__ :int=2 , __magic_name__ :List[str]=3 , __magic_name__ :Optional[int]=4 , __magic_name__ :str=2 , __magic_name__ :Any=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Dict=True , __magic_name__ :List[Any]=99 , __magic_name__ :Dict=36 , __magic_name__ :Optional[Any]=3 , __magic_name__ :str=4 , __magic_name__ :Optional[Any]=37 , __magic_name__ :Dict="gelu" , __magic_name__ :Any=0.1 , __magic_name__ :Union[str, Any]=0.1 , __magic_name__ :Dict=512 , __magic_name__ :str=16 , __magic_name__ :List[Any]=2 , __magic_name__ :Tuple=0.02 , __magic_name__ :Any=6 , __magic_name__ :Optional[int]=6 , __magic_name__ :Tuple=3 , __magic_name__ :str=4 , __magic_name__ :List[str]=None , __magic_name__ :str=1000 , ): '''simple docstring''' a = parent a = batch_size a = num_channels a = image_size a = patch_size a = text_seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = coordinate_size a = shape_size a = num_labels a = num_choices a = scope a = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) a = text_seq_length a = (image_size // patch_size) ** 2 + 1 a = self.text_seq_length + self.image_seq_length def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) a = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a = bbox[i, j, 3] a = bbox[i, j, 1] a = t if bbox[i, j, 2] < bbox[i, j, 0]: a = bbox[i, j, 2] a = bbox[i, j, 0] a = t a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.text_seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) a = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def lowerCamelCase__ ( self :int , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :List[str] , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int ): '''simple docstring''' a = LayoutLMvaModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # text + image a = model(__magic_name__ , pixel_values=__magic_name__ ) a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only a = model(__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only a = model(pixel_values=__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :List[Any] , __magic_name__ :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Union[str, Any] , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :List[str] , __magic_name__ :List[str] ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Dict , __magic_name__ :Optional[Any] , __magic_name__ :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :int , __magic_name__ :List[str] , __magic_name__ :Tuple ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :str , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :str , __magic_name__ :List[str] , __magic_name__ :Optional[int] , __magic_name__ :Optional[Any] ): '''simple docstring''' a = LayoutLMvaForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase__ = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :Optional[Any] , __magic_name__ :List[str] , __magic_name__ :List[Any] ): '''simple docstring''' return True def lowerCamelCase__ ( self :int ): '''simple docstring''' a = LayoutLMvaModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :Any=False ): '''simple docstring''' a = copy.deepcopy(__magic_name__ ) if model_class in get_values(__magic_name__ ): a = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__magic_name__ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__magic_name__ ): a = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in get_values(__magic_name__ ): a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__magic_name__ , ) return inputs_dict def lowerCamelCase__ ( self :str ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a = type self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def lowerCamelCase__ ( self :int ): '''simple docstring''' for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = LayoutLMvaModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def __A ( ) -> str: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__magic_name__ ) if is_vision_available() else None @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(__magic_name__ ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__magic_name__ , return_tensors="""pt""" ).pixel_values.to(__magic_name__ ) a = torch.tensor([[1, 2]] ) a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass a = model( input_ids=input_ids.to(__magic_name__ ) , bbox=bbox.to(__magic_name__ ) , pixel_values=pixel_values.to(__magic_name__ ) , ) # verify the logits a = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __magic_name__ ) a = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Optional[Any] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "MobileNetV2OnnxConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ["MobileNetV2FeatureExtractor"] __UpperCamelCase : Tuple = ["MobileNetV2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV2ForImageClassification", "MobileNetV2ForSemanticSegmentation", "MobileNetV2Model", "MobileNetV2PreTrainedModel", "load_tf_weights_in_mobilenet_v2", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
from copy import deepcopy class __lowerCAmelCase : def __init__( self :Union[str, Any] , __magic_name__ :list[int] | None = None , __magic_name__ :int | None = None ): '''simple docstring''' if arr is None and size is not None: a = size a = [0] * size elif arr is not None: self.init(__magic_name__ ) else: raise ValueError("""Either arr or size must be specified""" ) def lowerCamelCase__ ( self :Dict , __magic_name__ :list[int] ): '''simple docstring''' a = len(__magic_name__ ) a = deepcopy(__magic_name__ ) for i in range(1 , self.size ): a = self.next_(__magic_name__ ) if j < self.size: self.tree[j] += self.tree[i] def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): a = self.next_(__magic_name__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index + (index & (-index)) @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index - (index & (-index)) def lowerCamelCase__ ( self :Any , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value a = self.next_(__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' self.add(__magic_name__ , value - self.get(__magic_name__ ) ) def lowerCamelCase__ ( self :int , __magic_name__ :int ): '''simple docstring''' if right == 0: return 0 a = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] a = self.prev(__magic_name__ ) return result def lowerCamelCase__ ( self :int , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' return self.prefix(__magic_name__ ) - self.prefix(__magic_name__ ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :int ): '''simple docstring''' return self.query(__magic_name__ , index + 1 ) def lowerCamelCase__ ( self :Dict , __magic_name__ :int ): '''simple docstring''' value -= self.tree[0] if value < 0: return -1 a = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 a = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
347
1
def __A ( __lowerCamelCase ) -> list: a = len(__lowerCamelCase ) for i in range(1 , __lowerCamelCase ): a = collection[i] a = 0 a = i - 1 while low <= high: a = (low + high) // 2 if val < collection[mid]: a = mid - 1 else: a = mid + 1 for j in range(__lowerCamelCase , __lowerCamelCase , -1 ): a = collection[j - 1] a = val return collection if __name__ == "__main__": __UpperCamelCase : Union[str, Any] = input("Enter numbers separated by a comma:\n").strip() __UpperCamelCase : List[str] = [int(item) for item in user_input.split(",")] print(binary_insertion_sort(unsorted))
347
from __future__ import annotations from typing import Generic, TypeVar __UpperCamelCase : Union[str, Any] = TypeVar("T") class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple , __magic_name__ :T ): '''simple docstring''' a = data a = self a = 0 class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T ): '''simple docstring''' a = DisjointSetTreeNode(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :T ): '''simple docstring''' a = self.map[data] if elem_ref != elem_ref.parent: a = self.find_set(elem_ref.parent.data ) return elem_ref.parent def lowerCamelCase__ ( self :List[Any] , __magic_name__ :DisjointSetTreeNode[T] , __magic_name__ :DisjointSetTreeNode[T] ): '''simple docstring''' if nodea.rank > nodea.rank: a = nodea else: a = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T , __magic_name__ :T ): '''simple docstring''' self.link(self.find_set(__magic_name__ ) , self.find_set(__magic_name__ ) ) class __lowerCAmelCase ( Generic[T] ): def __init__( self :Union[str, Any] ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :T ): '''simple docstring''' if node not in self.connections: a = {} def lowerCamelCase__ ( self :Any , __magic_name__ :T , __magic_name__ :T , __magic_name__ :int ): '''simple docstring''' self.add_node(__magic_name__ ) self.add_node(__magic_name__ ) a = weight a = weight def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] a = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda __magic_name__ : x[2] ) # creating the disjoint set a = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__magic_name__ ) # MST generation a = 0 a = 0 a = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: a , a , a = edges[index] index += 1 a = disjoint_set.find_set(__magic_name__ ) a = disjoint_set.find_set(__magic_name__ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__magic_name__ , __magic_name__ , __magic_name__ ) disjoint_set.union(__magic_name__ , __magic_name__ ) return graph
347
1
from __future__ import annotations from decimal import Decimal from numpy import array def __A ( __lowerCamelCase ) -> list[list[float]]: a = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(__lowerCamelCase ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix a = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements a = [[0.0, 0.0], [0.0, 0.0]] a , a = matrix[1][1], matrix[0][0] a , a = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(__lowerCamelCase ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(__lowerCamelCase ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule a = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix a = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] a = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) a = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) a = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) a = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) a = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) a = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) a = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) a = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) a = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) a = array(__lowerCamelCase ) for i in range(3 ): for j in range(3 ): a = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix a = array(__lowerCamelCase ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(__lowerCamelCase ) # Calculate the inverse of the matrix return [[float(d(__lowerCamelCase ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
347
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = tempfile.mkdtemp() a = BlipImageProcessor() a = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) a = BlipProcessor(__magic_name__ , __magic_name__ ) processor.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self :List[Any] , **__magic_name__ :Union[str, Any] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).tokenizer def lowerCamelCase__ ( self :str , **__magic_name__ :List[str] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).image_processor def lowerCamelCase__ ( self :int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__magic_name__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) a = self.get_image_processor(do_normalize=__magic_name__ , padding_value=1.0 ) a = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__magic_name__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __magic_name__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = self.prepare_image_inputs() a = image_processor(__magic_name__ , return_tensors="""np""" ) a = processor(images=__magic_name__ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = processor(text=__magic_name__ ) a = tokenizer(__magic_name__ , return_token_type_ids=__magic_name__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(__magic_name__ ): processor() def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__magic_name__ ) a = tokenizer.batch_decode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
347
1
def __A ( __lowerCamelCase ) -> list[int]: a = [0 for i in range(len(__lowerCamelCase ) )] # initialize interval's left pointer and right pointer a , a = 0, 0 for i in range(1 , len(__lowerCamelCase ) ): # case when current index is inside the interval if i <= right_pointer: a = min(right_pointer - i + 1 , z_result[i - left_pointer] ) a = min_edge while go_next(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: a , a = i, i + z_result[i] - 1 return z_result def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> bool: return i + z_result[i] < len(__lowerCamelCase ) and s[z_result[i]] == s[i + z_result[i]] def __A ( __lowerCamelCase , __lowerCamelCase ) -> int: a = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string a = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(__lowerCamelCase ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
347
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : int = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class __lowerCAmelCase ( __magic_name__ , __magic_name__ ): UpperCamelCase__ = '''nat''' UpperCamelCase__ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self :Any , __magic_name__ :int=4 , __magic_name__ :Dict=3 , __magic_name__ :List[str]=64 , __magic_name__ :Optional[int]=[3, 4, 6, 5] , __magic_name__ :int=[2, 4, 8, 16] , __magic_name__ :str=7 , __magic_name__ :Tuple=3.0 , __magic_name__ :Dict=True , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.1 , __magic_name__ :Optional[Any]="gelu" , __magic_name__ :Optional[Any]=0.02 , __magic_name__ :Tuple=1E-5 , __magic_name__ :Union[str, Any]=0.0 , __magic_name__ :int=None , __magic_name__ :Any=None , **__magic_name__ :Dict , ): '''simple docstring''' super().__init__(**__magic_name__ ) a = patch_size a = num_channels a = embed_dim a = depths a = len(__magic_name__ ) a = num_heads a = kernel_size a = mlp_ratio a = qkv_bias a = hidden_dropout_prob a = attention_probs_dropout_prob a = drop_path_rate a = hidden_act a = layer_norm_eps a = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model a = int(embed_dim * 2 ** (len(__magic_name__ ) - 1) ) a = layer_scale_init_value a = ["""stem"""] + [F'stage{idx}' for idx in range(1 , len(__magic_name__ ) + 1 )] a , a = get_aligned_output_features_output_indices( out_features=__magic_name__ , out_indices=__magic_name__ , stage_names=self.stage_names )
347
1
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> np.ndarray: # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: a = ksize + 1 a = np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(__lowerCamelCase ): for x in range(__lowerCamelCase ): # distance from center a = x - ksize // 2 a = y - ksize // 2 # degree to radiant a = theta / 180 * np.pi a = np.cos(_theta ) a = np.sin(_theta ) # get kernel x a = cos_theta * px + sin_theta * py # get kernel y a = -sin_theta * px + cos_theta * py # fill kernel a = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __UpperCamelCase : Any = imread("../image_data/lena.jpg") # turn image in gray scale value __UpperCamelCase : List[str] = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __UpperCamelCase : str = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: __UpperCamelCase : Optional[Any] = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __UpperCamelCase : str = out / out.max() * 255 __UpperCamelCase : Tuple = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
347
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer a = flax_key_tuple[:-1] + ("""weight""",) a = torch.permute(__lowerCamelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCamelCase ): # linear layer a = flax_key_tuple[:-1] + ("""weight""",) a = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: a = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: if "metadata" in layer: a = layer.split("""metadata""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: a = layer.split("""kvstore""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: a = layer.split("""/""" ) a = """/""".join(split_layer[:-1] ) a = (split_layer[-1],) if "kvstore/path" in layer: a = f'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: a = """file""" else: a = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __A ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: a = rename_keys(__lowerCamelCase ) a = {} for k, v in current_block.items(): a = v a = new_current_block torch.save(__lowerCamelCase , __lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = WEIGHTS_NAME ) -> List[str]: a = convert_file_size_to_int(__lowerCamelCase ) a = [] a = {} a = 0 a = 0 os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: a = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] a = flatten_dict(__lowerCamelCase , sep="""/""" ) a = {} for layer in checkpoint_info.keys(): a , a , a = get_key_and_tensorstore_dict( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if curr_real_layer_name in all_layers: a = content else: a = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() a = torch.tensor(__lowerCamelCase ) a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts a , a = rename_base_flax_keys(tuple(key.split("""/""" ) ) , __lowerCamelCase ) a = """/""".join(__lowerCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: a = os.path.join( __lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block a = {} a = 0 a = raw_weights.to(getattr(__lowerCamelCase , __lowerCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index a = {} a = {} for idx, shard in enumerate(__lowerCamelCase ): a = weights_name.replace( """.bin""" , f'-{idx+1:05d}-of-{len(__lowerCamelCase ):05d}.bin' ) # len(sharded_state_dicts):05d} a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{idx+1:05d}-of-???.bin' ) ) os.rename(__lowerCamelCase , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) a = shard for key in shard: a = shard_file # Add the metadata a = {"""total_size""": total_size} a = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(__lowerCamelCase , __lowerCamelCase ) , """w""" , encoding="""utf-8""" ) as f: a = json.dumps(__lowerCamelCase , indent=2 , sort_keys=__lowerCamelCase ) + """\n""" f.write(__lowerCamelCase ) return metadata, index if __name__ == "__main__": __UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __UpperCamelCase : Any = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __A ( ) -> Tuple: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer a = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) a = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) a = TaTokenizer.from_pretrained("""t5-small""" ) a = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" a = tokenizer(__lowerCamelCase , return_tensors="""pt""" ).input_ids a = model.generate(__lowerCamelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
347
1
from argparse import ArgumentParser from . import BaseTransformersCLICommand def __A ( __lowerCamelCase ) -> Optional[Any]: return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCAmelCase ( __magic_name__ ): @staticmethod def lowerCamelCase__ ( __magic_name__ :ArgumentParser ): '''simple docstring''' a = parser.add_parser("""download""" ) download_parser.add_argument( """--cache-dir""" , type=__magic_name__ , default=__magic_name__ , help="""Path to location to store the models""" ) download_parser.add_argument( """--force""" , action="""store_true""" , help="""Force the model to be download even if already in cache-dir""" ) download_parser.add_argument( """--trust-remote-code""" , action="""store_true""" , help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine""" , ) download_parser.add_argument("""model""" , type=__magic_name__ , help="""Name of the model to download""" ) download_parser.set_defaults(func=__magic_name__ ) def __init__( self :List[str] , __magic_name__ :str , __magic_name__ :str , __magic_name__ :bool , __magic_name__ :bool ): '''simple docstring''' a = model a = cache a = force a = trust_remote_code def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
347
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __UpperCamelCase : Union[str, Any] = (720, 1_280) # Height, Width __UpperCamelCase : Any = (0.4, 0.6) # if height or width lower than this scale, drop it. __UpperCamelCase : str = 1 / 100 __UpperCamelCase : Optional[int] = "" __UpperCamelCase : List[Any] = "" __UpperCamelCase : Union[str, Any] = "" __UpperCamelCase : Tuple = 250 def __A ( ) -> None: a , a = get_dataset(__lowerCamelCase , __lowerCamelCase ) for index in range(__lowerCamelCase ): a = random.sample(range(len(__lowerCamelCase ) ) , 4 ) a , a , a = update_image_and_anno( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , filter_scale=__lowerCamelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' a = random_chars(32 ) a = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] a = f'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(f'{file_root}.jpg' , __lowerCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) a = [] for anno in new_annos: a = anno[3] - anno[1] a = anno[4] - anno[2] a = anno[1] + width / 2 a = anno[2] + height / 2 a = f'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(__lowerCamelCase ) with open(f'{file_root}.txt' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> tuple[list, list]: a = [] a = [] for label_file in glob.glob(os.path.join(__lowerCamelCase , """*.txt""" ) ): a = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCamelCase ) as in_file: a = in_file.readlines() a = os.path.join(__lowerCamelCase , f'{label_name}.jpg' ) a = [] for obj_list in obj_lists: a = obj_list.rstrip("""\n""" ).split(""" """ ) a = float(obj[1] ) - float(obj[3] ) / 2 a = float(obj[2] ) - float(obj[4] ) / 2 a = float(obj[1] ) + float(obj[3] ) / 2 a = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__lowerCamelCase ) labels.append(__lowerCamelCase ) return img_paths, labels def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 0.0 , ) -> tuple[list, list, str]: a = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = int(scale_x * output_size[1] ) a = int(scale_y * output_size[0] ) a = [] a = [] for i, index in enumerate(__lowerCamelCase ): a = all_img_list[index] path_list.append(__lowerCamelCase ) a = all_annos[index] a = cva.imread(__lowerCamelCase ) if i == 0: # top-left a = cva.resize(__lowerCamelCase , (divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = bbox[2] * scale_y a = bbox[3] * scale_x a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right a = cva.resize(__lowerCamelCase , (output_size[1] - divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = bbox[2] * scale_y a = scale_x + bbox[3] * (1 - scale_x) a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left a = cva.resize(__lowerCamelCase , (divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = scale_y + bbox[2] * (1 - scale_y) a = bbox[3] * scale_x a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right a = cva.resize( __lowerCamelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = scale_y + bbox[2] * (1 - scale_y) a = scale_x + bbox[3] * (1 - scale_x) a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: a = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __A ( __lowerCamelCase ) -> str: assert number_char > 1, "The number of character should greater than 1" a = ascii_lowercase + digits return "".join(random.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
347
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : int = { "vinvino02/glpn-kitti": "https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json", # See all GLPN models at https://huggingface.co/models?filter=glpn } class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''glpn''' def __init__( self :Optional[int] , __magic_name__ :Union[str, Any]=3 , __magic_name__ :Union[str, Any]=4 , __magic_name__ :Dict=[2, 2, 2, 2] , __magic_name__ :List[Any]=[8, 4, 2, 1] , __magic_name__ :Any=[32, 64, 160, 256] , __magic_name__ :List[Any]=[7, 3, 3, 3] , __magic_name__ :Optional[int]=[4, 2, 2, 2] , __magic_name__ :int=[1, 2, 5, 8] , __magic_name__ :Tuple=[4, 4, 4, 4] , __magic_name__ :str="gelu" , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[str]=0.02 , __magic_name__ :List[str]=0.1 , __magic_name__ :Optional[Any]=1E-6 , __magic_name__ :Union[str, Any]=64 , __magic_name__ :Optional[int]=10 , __magic_name__ :List[str]=-1 , **__magic_name__ :List[str] , ): '''simple docstring''' super().__init__(**__magic_name__ ) a = num_channels a = num_encoder_blocks a = depths a = sr_ratios a = hidden_sizes a = patch_sizes a = strides a = mlp_ratios a = num_attention_heads a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = initializer_range a = drop_path_rate a = layer_norm_eps a = decoder_hidden_size a = max_depth a = head_in_index
347
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Optional[Any] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "MobileNetV2OnnxConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ["MobileNetV2FeatureExtractor"] __UpperCamelCase : Tuple = ["MobileNetV2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV2ForImageClassification", "MobileNetV2ForSemanticSegmentation", "MobileNetV2Model", "MobileNetV2PreTrainedModel", "load_tf_weights_in_mobilenet_v2", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
import math from collections.abc import Iterator from itertools import takewhile def __A ( __lowerCamelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__lowerCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __A ( ) -> Iterator[int]: a = 2 while True: if is_prime(__lowerCamelCase ): yield num num += 1 def __A ( __lowerCamelCase = 200_0000 ) -> int: return sum(takewhile(lambda __lowerCamelCase : x < n , prime_generator() ) ) if __name__ == "__main__": print(F'{solution() = }')
347
def __A ( __lowerCamelCase ) -> bool: if num < 0: return False a = num a = 0 while num > 0: a = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
1
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets __UpperCamelCase : List[Any] = "\\n@inproceedings{lin-2004-rouge,\n title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",\n author = \"Lin, Chin-Yew\",\n booktitle = \"Text Summarization Branches Out\",\n month = jul,\n year = \"2004\",\n address = \"Barcelona, Spain\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W04-1013\",\n pages = \"74--81\",\n}\n" __UpperCamelCase : List[Any] = "\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n" __UpperCamelCase : Any = "\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,\n `\"rougeL\"`: Longest common subsequence based scoring.\n `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric('rouge')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']\n >>> print(results[\"rouge1\"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results[\"rouge1\"].mid.fmeasure)\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/google-research/tree/master/rouge"""] , reference_urls=[ """https://en.wikipedia.org/wiki/ROUGE_(metric)""", """https://github.com/google-research/google-research/tree/master/rouge""", ] , ) def lowerCamelCase__ ( self :str , __magic_name__ :Union[str, Any] , __magic_name__ :str , __magic_name__ :Tuple=None , __magic_name__ :str=True , __magic_name__ :Union[str, Any]=False ): '''simple docstring''' if rouge_types is None: a = ["""rouge1""", """rouge2""", """rougeL""", """rougeLsum"""] a = rouge_scorer.RougeScorer(rouge_types=__magic_name__ , use_stemmer=__magic_name__ ) if use_aggregator: a = scoring.BootstrapAggregator() else: a = [] for ref, pred in zip(__magic_name__ , __magic_name__ ): a = scorer.score(__magic_name__ , __magic_name__ ) if use_aggregator: aggregator.add_scores(__magic_name__ ) else: scores.append(__magic_name__ ) if use_aggregator: a = aggregator.aggregate() else: a = {} for key in scores[0]: a = [score[key] for score in scores] return result
347
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = CanineTokenizer UpperCamelCase__ = False def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().setUp() a = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return CanineTokenizer.from_pretrained("""google/canine-s""" ) def lowerCamelCase__ ( self :Tuple , **__magic_name__ :Dict ): '''simple docstring''' a = self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) a = 1024 return tokenizer @require_torch def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.canine_tokenizer a = ["""Life is like a box of chocolates.""", """You never know what you're gonna get."""] # fmt: off a = [5_7344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 5_7345, 0, 0, 0, 0] # fmt: on a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) self.assertIsInstance(__magic_name__ , __magic_name__ ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = ["""Once there was a man.""", """He wrote a test in HuggingFace Tranformers."""] a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("""input_ids""" , __magic_name__ ) self.assertIn("""attention_mask""" , __magic_name__ ) self.assertIn("""token_type_ids""" , __magic_name__ ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = [ """What's the weater?""", """It's about 25 degrees.""", ] a = tokenizer( text_target=__magic_name__ , max_length=32 , padding="""max_length""" , truncation=__magic_name__ , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) shutil.rmtree(__magic_name__ ) a = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: a = chr(0Xe_0_0_7 ) additional_special_tokens.append(__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertIn(__magic_name__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) a = tokenizer.__class__.from_pretrained(__magic_name__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a , a = self.get_clean_sequence(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_5 a = chr(__magic_name__ ) tokenizer.add_special_tokens({"""cls_token""": special_token} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) a = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , input_encoded + special_token_id ) a = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertTrue(special_token not in decoded ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = chr(0Xe_0_0_5 ) a = chr(0Xe_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=__magic_name__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"""additional_special_tokens""": [SPECIAL_TOKEN_2]} ) a = tokenizer.tokenize(__magic_name__ ) a = tokenizer.tokenize(__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(token_a[0] , __magic_name__ ) self.assertEqual(token_a[0] , __magic_name__ ) @require_tokenizers def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(__magic_name__ ) tokenizer.from_pretrained(__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__magic_name__ ) with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = [new_token_a] a = [new_token_a] with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files a = tokenizer_class.from_pretrained(__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) a = 0Xe_0_0_7 a = chr(__magic_name__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained a = [AddedToken(__magic_name__ , lstrip=__magic_name__ )] a = tokenizer_class.from_pretrained( __magic_name__ , additional_special_tokens=__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = """hello world""" if self.space_between_special_tokens: a = """[CLS] hello world [SEP]""" else: a = input a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.decode(__magic_name__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(__magic_name__ , [output, output.lower()] ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = [ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] a = """a""" a = ord(__magic_name__ ) for attr in attributes_list: setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [] ) a = 0Xe_0_0_6 a = chr(__magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [additional_special_token_id] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [additional_special_token] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [additional_special_token_id] ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :str ): '''simple docstring''' pass def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass
347
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __UpperCamelCase : Optional[int] = logging.get_logger(__name__) __UpperCamelCase : Optional[int] = OrderedDict( [ ("align", "EfficientNetImageProcessor"), ("beit", "BeitImageProcessor"), ("bit", "BitImageProcessor"), ("blip", "BlipImageProcessor"), ("blip-2", "BlipImageProcessor"), ("bridgetower", "BridgeTowerImageProcessor"), ("chinese_clip", "ChineseCLIPImageProcessor"), ("clip", "CLIPImageProcessor"), ("clipseg", "ViTImageProcessor"), ("conditional_detr", "ConditionalDetrImageProcessor"), ("convnext", "ConvNextImageProcessor"), ("convnextv2", "ConvNextImageProcessor"), ("cvt", "ConvNextImageProcessor"), ("data2vec-vision", "BeitImageProcessor"), ("deformable_detr", "DeformableDetrImageProcessor"), ("deit", "DeiTImageProcessor"), ("deta", "DetaImageProcessor"), ("detr", "DetrImageProcessor"), ("dinat", "ViTImageProcessor"), ("donut-swin", "DonutImageProcessor"), ("dpt", "DPTImageProcessor"), ("efficientformer", "EfficientFormerImageProcessor"), ("efficientnet", "EfficientNetImageProcessor"), ("flava", "FlavaImageProcessor"), ("focalnet", "BitImageProcessor"), ("git", "CLIPImageProcessor"), ("glpn", "GLPNImageProcessor"), ("groupvit", "CLIPImageProcessor"), ("imagegpt", "ImageGPTImageProcessor"), ("instructblip", "BlipImageProcessor"), ("layoutlmv2", "LayoutLMv2ImageProcessor"), ("layoutlmv3", "LayoutLMv3ImageProcessor"), ("levit", "LevitImageProcessor"), ("mask2former", "Mask2FormerImageProcessor"), ("maskformer", "MaskFormerImageProcessor"), ("mgp-str", "ViTImageProcessor"), ("mobilenet_v1", "MobileNetV1ImageProcessor"), ("mobilenet_v2", "MobileNetV2ImageProcessor"), ("mobilevit", "MobileViTImageProcessor"), ("mobilevit", "MobileViTImageProcessor"), ("mobilevitv2", "MobileViTImageProcessor"), ("nat", "ViTImageProcessor"), ("oneformer", "OneFormerImageProcessor"), ("owlvit", "OwlViTImageProcessor"), ("perceiver", "PerceiverImageProcessor"), ("pix2struct", "Pix2StructImageProcessor"), ("poolformer", "PoolFormerImageProcessor"), ("regnet", "ConvNextImageProcessor"), ("resnet", "ConvNextImageProcessor"), ("sam", "SamImageProcessor"), ("segformer", "SegformerImageProcessor"), ("swiftformer", "ViTImageProcessor"), ("swin", "ViTImageProcessor"), ("swin2sr", "Swin2SRImageProcessor"), ("swinv2", "ViTImageProcessor"), ("table-transformer", "DetrImageProcessor"), ("timesformer", "VideoMAEImageProcessor"), ("tvlt", "TvltImageProcessor"), ("upernet", "SegformerImageProcessor"), ("van", "ConvNextImageProcessor"), ("videomae", "VideoMAEImageProcessor"), ("vilt", "ViltImageProcessor"), ("vit", "ViTImageProcessor"), ("vit_hybrid", "ViTHybridImageProcessor"), ("vit_mae", "ViTImageProcessor"), ("vit_msn", "ViTImageProcessor"), ("xclip", "CLIPImageProcessor"), ("yolos", "YolosImageProcessor"), ] ) __UpperCamelCase : Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def __A ( __lowerCamelCase ) -> Dict: for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a = model_type_to_module_name(__lowerCamelCase ) a = importlib.import_module(f'.{module_name}' , """transformers.models""" ) try: return getattr(__lowerCamelCase , __lowerCamelCase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(__lowerCamelCase , """__name__""" , __lowerCamelCase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a = importlib.import_module("""transformers""" ) if hasattr(__lowerCamelCase , __lowerCamelCase ): return getattr(__lowerCamelCase , __lowerCamelCase ) return None def __A ( __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , **__lowerCamelCase , ) -> Tuple: a = get_file_from_repo( __lowerCamelCase , __lowerCamelCase , cache_dir=__lowerCamelCase , force_download=__lowerCamelCase , resume_download=__lowerCamelCase , proxies=__lowerCamelCase , use_auth_token=__lowerCamelCase , revision=__lowerCamelCase , local_files_only=__lowerCamelCase , ) if resolved_config_file is None: logger.info( """Could not locate the image processor configuration file, will try to use the model config instead.""" ) return {} with open(__lowerCamelCase , encoding="""utf-8""" ) as reader: return json.load(__lowerCamelCase ) class __lowerCAmelCase : def __init__( self :List[Any] ): '''simple docstring''' raise EnvironmentError( """AutoImageProcessor is designed to be instantiated """ """using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.""" ) @classmethod @replace_list_option_in_docstrings(__magic_name__ ) def lowerCamelCase__ ( cls :str , __magic_name__ :Any , **__magic_name__ :List[Any] ): '''simple docstring''' a = kwargs.pop("""config""" , __magic_name__ ) a = kwargs.pop("""trust_remote_code""" , __magic_name__ ) a = True a , a = ImageProcessingMixin.get_image_processor_dict(__magic_name__ , **__magic_name__ ) a = config_dict.get("""image_processor_type""" , __magic_name__ ) a = None if "AutoImageProcessor" in config_dict.get("""auto_map""" , {} ): a = config_dict["""auto_map"""]["""AutoImageProcessor"""] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a = config_dict.pop("""feature_extractor_type""" , __magic_name__ ) if feature_extractor_class is not None: logger.warning( """Could not find image processor class in the image processor config or the model config. Loading""" """ based on pattern matching with the model's feature extractor configuration.""" ) a = feature_extractor_class.replace("""FeatureExtractor""" , """ImageProcessor""" ) if "AutoFeatureExtractor" in config_dict.get("""auto_map""" , {} ): a = config_dict["""auto_map"""]["""AutoFeatureExtractor"""] a = feature_extractor_auto_map.replace("""FeatureExtractor""" , """ImageProcessor""" ) logger.warning( """Could not find image processor auto map in the image processor config or the model config.""" """ Loading based on pattern matching with the model's feature extractor configuration.""" ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__magic_name__ , __magic_name__ ): a = AutoConfig.from_pretrained(__magic_name__ , **__magic_name__ ) # It could be in `config.image_processor_type`` a = getattr(__magic_name__ , """image_processor_type""" , __magic_name__ ) if hasattr(__magic_name__ , """auto_map""" ) and "AutoImageProcessor" in config.auto_map: a = config.auto_map["""AutoImageProcessor"""] if image_processor_class is not None: a = image_processor_class_from_name(__magic_name__ ) a = image_processor_auto_map is not None a = image_processor_class is not None or type(__magic_name__ ) in IMAGE_PROCESSOR_MAPPING a = resolve_trust_remote_code( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) if has_remote_code and trust_remote_code: a = get_class_from_dynamic_module( __magic_name__ , __magic_name__ , **__magic_name__ ) a = kwargs.pop("""code_revision""" , __magic_name__ ) if os.path.isdir(__magic_name__ ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__magic_name__ , **__magic_name__ ) elif image_processor_class is not None: return image_processor_class.from_dict(__magic_name__ , **__magic_name__ ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__magic_name__ ) in IMAGE_PROCESSOR_MAPPING: a = IMAGE_PROCESSOR_MAPPING[type(__magic_name__ )] return image_processor_class.from_dict(__magic_name__ , **__magic_name__ ) raise ValueError( F'Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ' F'`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ' F'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}' ) @staticmethod def lowerCamelCase__ ( __magic_name__ :Any , __magic_name__ :List[str] ): '''simple docstring''' IMAGE_PROCESSOR_MAPPING.register(__magic_name__ , __magic_name__ )
347
def __A ( __lowerCamelCase ) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
347
1
from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : def __init__( self :Dict , __magic_name__ :Optional[Any] , __magic_name__ :List[Any]=13 , __magic_name__ :Union[str, Any]=30 , __magic_name__ :Optional[int]=2 , __magic_name__ :List[str]=3 , __magic_name__ :Any=True , __magic_name__ :int=True , __magic_name__ :Optional[Any]=32 , __magic_name__ :Any=2 , __magic_name__ :List[str]=4 , __magic_name__ :Optional[int]=37 , __magic_name__ :Optional[int]="gelu" , __magic_name__ :Dict=0.1 , __magic_name__ :Any=0.1 , __magic_name__ :Optional[int]=10 , __magic_name__ :List[Any]=0.02 , __magic_name__ :Union[str, Any]=3 , __magic_name__ :Dict=0.6 , __magic_name__ :Tuple=None , ): '''simple docstring''' a = parent a = batch_size a = image_size a = patch_size a = num_channels a = is_training a = use_labels a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = type_sequence_label_size a = initializer_range a = mask_ratio a = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) a = (image_size // patch_size) ** 2 a = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__magic_name__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase__ ( self :Dict , __magic_name__ :List[str] , __magic_name__ :List[str] , __magic_name__ :Any ): '''simple docstring''' a = TFViTMAEModel(config=__magic_name__ ) a = model(__magic_name__ , training=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :str , __magic_name__ :Dict , __magic_name__ :Optional[Any] ): '''simple docstring''' a = TFViTMAEForPreTraining(__magic_name__ ) a = model(__magic_name__ , training=__magic_name__ ) # expected sequence length = num_patches a = (self.image_size // self.patch_size) ** 2 a = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images a = 1 a = TFViTMAEForPreTraining(__magic_name__ ) a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a = model(__magic_name__ , training=__magic_name__ ) a = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.prepare_config_and_inputs() ((a) , (a) , (a)) = config_and_inputs a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () UpperCamelCase__ = {'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {} UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = TFViTMAEModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def lowerCamelCase__ ( self :int ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , tf.keras.layers.Layer ) ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :str ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' np.random.seed(2 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = int((config.image_size // config.patch_size) ** 2 ) a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = model(__magic_name__ , noise=__magic_name__ ) a = copy.deepcopy(self._prepare_for_class(__magic_name__ , __magic_name__ ) ) a = model(**__magic_name__ , noise=__magic_name__ ) a = outputs_dict[0].numpy() a = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1E-6 ) def lowerCamelCase__ ( self :int ): '''simple docstring''' np.random.seed(2 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = int((config.image_size // config.patch_size) ** 2 ) a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(__magic_name__ :str ): a = {} for k, v in inputs_dict.items(): if tf.is_tensor(__magic_name__ ): a = v.numpy() else: a = np.array(__magic_name__ ) return inputs_np_dict for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = prepare_numpy_arrays(__magic_name__ ) a = model(__magic_name__ , noise=__magic_name__ ) a = model(**__magic_name__ , noise=__magic_name__ ) self.assert_outputs_same(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :Optional[int] , __magic_name__ :List[str] , __magic_name__ :Union[str, Any] ): '''simple docstring''' np.random.seed(2 ) a = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) a = tf.constant(__magic_name__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument a = tf_noise super().check_pt_tf_models(__magic_name__ , __magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' np.random.seed(2 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(__magic_name__ ) if module_member_name.endswith("""MainLayer""" ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len("""MainLayer""" )] == model_class.__name__[: -len("""Model""" )] for module_member in (getattr(__magic_name__ , __magic_name__ ),) if isinstance(__magic_name__ , __magic_name__ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(__magic_name__ , """_keras_serializable""" , __magic_name__ ) } a = int((config.image_size // config.patch_size) ** 2 ) a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) a = tf.convert_to_tensor(__magic_name__ ) inputs_dict.update({"""noise""": noise} ) for main_layer_class in tf_main_layer_classes: a = main_layer_class(__magic_name__ ) a = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } a = tf.keras.Model(__magic_name__ , outputs=main_layer(__magic_name__ ) ) a = model(__magic_name__ ) with tempfile.TemporaryDirectory() as tmpdirname: a = os.path.join(__magic_name__ , """keras_model.h5""" ) model.save(__magic_name__ ) a = tf.keras.models.load_model( __magic_name__ , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(__magic_name__ , tf.keras.Model ) a = model(__magic_name__ ) self.assert_outputs_same(__magic_name__ , __magic_name__ ) @slow def lowerCamelCase__ ( self :str ): '''simple docstring''' np.random.seed(2 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = int((config.image_size // config.patch_size) ** 2 ) a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = model(__magic_name__ , noise=__magic_name__ ) if model_class.__name__ == "TFViTMAEModel": a = outputs.last_hidden_state.numpy() a = 0 else: a = outputs.logits.numpy() a = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__magic_name__ , saved_model=__magic_name__ ) a = model_class.from_pretrained(__magic_name__ ) a = model(__magic_name__ , noise=__magic_name__ ) if model_class.__name__ == "TFViTMAEModel": a = after_outputs["""last_hidden_state"""].numpy() a = 0 else: a = after_outputs["""logits"""].numpy() a = 0 a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__magic_name__ , 1E-5 ) def lowerCamelCase__ ( self :str ): '''simple docstring''' np.random.seed(2 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = int((config.image_size // config.patch_size) ** 2 ) a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = model(__magic_name__ , noise=__magic_name__ ) a = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(__magic_name__ ) a = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config a = model_class.from_config(model.config ) a = new_model(__magic_name__ ) # Build model new_model.set_weights(model.get_weights() ) a = new_model(__magic_name__ , noise=__magic_name__ ) self.assert_outputs_same(__magic_name__ , __magic_name__ ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' pass @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(__magic_name__ ) def __A ( ) -> int: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' np.random.seed(2 ) a = TFViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__magic_name__ , return_tensors="""tf""" ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) a = ViTMAEConfig() a = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) a = np.random.uniform(size=(1, num_patches) ) # forward pass a = model(**__magic_name__ , noise=__magic_name__ ) # verify the logits a = tf.convert_to_tensor([1, 196, 768] ) self.assertEqual(outputs.logits.shape , __magic_name__ ) a = tf.convert_to_tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , __magic_name__ , atol=1E-4 )
347
def __A ( __lowerCamelCase ) -> int: if not numbers: return 0 if not isinstance(__lowerCamelCase , (list, tuple) ) or not all( isinstance(__lowerCamelCase , __lowerCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) a = a = a = numbers[0] for i in range(1 , len(__lowerCamelCase ) ): # update the maximum and minimum subarray products a = numbers[i] if number < 0: a , a = min_till_now, max_till_now a = max(__lowerCamelCase , max_till_now * number ) a = min(__lowerCamelCase , min_till_now * number ) # update the maximum product found till now a = max(__lowerCamelCase , __lowerCamelCase ) return max_prod
347
1
import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __lowerCAmelCase : def __init__( self :Union[str, Any] , __magic_name__ :List[Any] , __magic_name__ :Optional[Any]=sys.maxsize ): '''simple docstring''' a = """bilinear""" a = max_size a = short_edge_length def __call__( self :Optional[int] , __magic_name__ :Dict ): '''simple docstring''' a = [] for img in imgs: a , a = img.shape[:2] # later: provide list and randomly choose index for resize a = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img a = size * 1.0 / min(__magic_name__ , __magic_name__ ) if h < w: a , a = size, scale * w else: a , a = scale * h, size if max(__magic_name__ , __magic_name__ ) > self.max_size: a = self.max_size * 1.0 / max(__magic_name__ , __magic_name__ ) a = newh * scale a = neww * scale a = int(neww + 0.5 ) a = int(newh + 0.5 ) if img.dtype == np.uinta: a = Image.fromarray(__magic_name__ ) a = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) a = np.asarray(__magic_name__ ) else: a = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw a = nn.functional.interpolate( __magic_name__ , (newh, neww) , mode=self.interp_method , align_corners=__magic_name__ ).squeeze(0 ) img_augs.append(__magic_name__ ) return img_augs class __lowerCAmelCase : def __init__( self :Union[str, Any] , __magic_name__ :str ): '''simple docstring''' a = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) a = cfg.INPUT.FORMAT a = cfg.SIZE_DIVISIBILITY a = cfg.PAD_VALUE a = cfg.INPUT.MAX_SIZE_TEST a = cfg.MODEL.DEVICE a = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) a = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) a = lambda __magic_name__ : (x - self.pixel_mean) / self.pixel_std def lowerCamelCase__ ( self :List[Any] , __magic_name__ :str ): '''simple docstring''' a = tuple(max(__magic_name__ ) for s in zip(*[img.shape for img in images] ) ) a = [im.shape[-2:] for im in images] a = [ nn.functional.pad( __magic_name__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(__magic_name__ , __magic_name__ ) ] return torch.stack(__magic_name__ ), torch.tensor(__magic_name__ ) def __call__( self :str , __magic_name__ :str , __magic_name__ :List[Any]=False ): '''simple docstring''' with torch.no_grad(): if not isinstance(__magic_name__ , __magic_name__ ): a = [images] if single_image: assert len(__magic_name__ ) == 1 for i in range(len(__magic_name__ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(__magic_name__ , images.pop(__magic_name__ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( __magic_name__ , torch.as_tensor(img_tensorize(images.pop(__magic_name__ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge a = torch.tensor([im.shape[:2] for im in images] ) a = self.aug(__magic_name__ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic a = [self.normalizer(__magic_name__ ) for x in images] # now pad them to do the following operations a , a = self.pad(__magic_name__ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad a = torch.true_divide(__magic_name__ , __magic_name__ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def __A ( __lowerCamelCase , __lowerCamelCase ) -> Tuple: boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: assert torch.isfinite(__lowerCamelCase ).all(), "Box tensor contains infinite or NaN!" a , a = box_size tensor[:, 0].clamp_(min=0 , max=__lowerCamelCase ) tensor[:, 1].clamp_(min=0 , max=__lowerCamelCase ) tensor[:, 2].clamp_(min=0 , max=__lowerCamelCase ) tensor[:, 3].clamp_(min=0 , max=__lowerCamelCase )
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCamelCase : Optional[Any] = { "configuration_wav2vec2": ["WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2Config"], "feature_extraction_wav2vec2": ["Wav2Vec2FeatureExtractor"], "processing_wav2vec2": ["Wav2Vec2Processor"], "tokenization_wav2vec2": ["Wav2Vec2CTCTokenizer", "Wav2Vec2Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = [ "WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ForAudioFrameClassification", "Wav2Vec2ForCTC", "Wav2Vec2ForMaskedLM", "Wav2Vec2ForPreTraining", "Wav2Vec2ForSequenceClassification", "Wav2Vec2ForXVector", "Wav2Vec2Model", "Wav2Vec2PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ "TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWav2Vec2ForCTC", "TFWav2Vec2Model", "TFWav2Vec2PreTrainedModel", "TFWav2Vec2ForSequenceClassification", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "FlaxWav2Vec2ForCTC", "FlaxWav2Vec2ForPreTraining", "FlaxWav2Vec2Model", "FlaxWav2Vec2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase : int = logging.get_logger(__name__) __UpperCamelCase : Union[str, Any] = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''segformer''' def __init__( self :Dict , __magic_name__ :List[str]=3 , __magic_name__ :int=4 , __magic_name__ :Union[str, Any]=[2, 2, 2, 2] , __magic_name__ :List[Any]=[8, 4, 2, 1] , __magic_name__ :str=[32, 64, 160, 256] , __magic_name__ :int=[7, 3, 3, 3] , __magic_name__ :Dict=[4, 2, 2, 2] , __magic_name__ :List[Any]=[1, 2, 5, 8] , __magic_name__ :int=[4, 4, 4, 4] , __magic_name__ :Union[str, Any]="gelu" , __magic_name__ :Any=0.0 , __magic_name__ :Optional[int]=0.0 , __magic_name__ :List[Any]=0.1 , __magic_name__ :str=0.02 , __magic_name__ :List[str]=0.1 , __magic_name__ :Any=1E-6 , __magic_name__ :Optional[int]=256 , __magic_name__ :Tuple=255 , **__magic_name__ :Tuple , ): '''simple docstring''' super().__init__(**__magic_name__ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __magic_name__ , ) a = num_channels a = num_encoder_blocks a = depths a = sr_ratios a = hidden_sizes a = patch_sizes a = strides a = mlp_ratios a = num_attention_heads a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = classifier_dropout_prob a = initializer_range a = drop_path_rate a = layer_norm_eps a = decoder_hidden_size a = kwargs.get("""reshape_last_stage""" , __magic_name__ ) a = semantic_loss_ignore_index class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = version.parse('''1.11''' ) @property def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' return 1E-4 @property def lowerCamelCase__ ( self :str ): '''simple docstring''' return 12
347
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCamelCase ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(__lowerCamelCase ) assert result == expected
347
1
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __UpperCamelCase : Dict = "%20".join(argv[1:]) if len(argv) > 1 else quote(str(input("Search: "))) print("Googling.....") __UpperCamelCase : Dict = F'https://www.google.com/search?q={query}&num=100' __UpperCamelCase : List[str] = requests.get( url, headers={"User-Agent": str(UserAgent().random)}, ) try: __UpperCamelCase : Union[str, Any] = ( BeautifulSoup(res.text, "html.parser") .find("div", attrs={"class": "yuRUbf"}) .find("a") .get("href") ) except AttributeError: __UpperCamelCase : Tuple = parse_qs( BeautifulSoup(res.text, "html.parser") .find("div", attrs={"class": "kCrYT"}) .find("a") .get("href") )["url"][0] webbrowser.open(link)
347
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __A ( __lowerCamelCase ) -> bool: a = int(number**0.5 ) return number == sq * sq def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> tuple[int, int]: a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den a = x_den * y_den * z_den a = gcd(__lowerCamelCase , __lowerCamelCase ) top //= hcf bottom //= hcf return top, bottom def __A ( __lowerCamelCase = 35 ) -> int: a = set() a = 42 a = Fraction(0 ) a = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 a = x_num * y_den + x_den * y_num a = x_den * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) a = x_den * x_den * y_den * y_den if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=-1 a = x_num * y_num a = x_den * y_num + x_num * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = x_num * x_num * y_num * y_num a = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) for num, den in unique_s: total += Fraction(__lowerCamelCase , __lowerCamelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(F'{solution() = }')
347
1
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = """ylacombe/bark-small""" a = tempfile.mkdtemp() a = """en_speaker_1""" a = """This is a test string""" a = """speaker_embeddings_path.json""" a = """speaker_embeddings""" def lowerCamelCase__ ( self :Tuple , **__magic_name__ :Dict ): '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **__magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_tokenizer() a = BarkProcessor(tokenizer=__magic_name__ ) processor.save_pretrained(self.tmpdirname ) a = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def lowerCamelCase__ ( self :str ): '''simple docstring''' a = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) a = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) a = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) a = 35 a = 2 a = 8 a = { """semantic_prompt""": np.ones(__magic_name__ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset a = processor(text=self.input_string , voice_preset=__magic_name__ ) a = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__magic_name__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file a = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(__magic_name__ , **__magic_name__ ) a = processor(text=self.input_string , voice_preset=__magic_name__ ) a = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__magic_name__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub a = processor(text=self.input_string , voice_preset=self.voice_preset ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.get_tokenizer() a = BarkProcessor(tokenizer=__magic_name__ ) a = processor(text=self.input_string ) a = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=__magic_name__ , return_attention_mask=__magic_name__ , return_token_type_ids=__magic_name__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
347
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :List[str] , __magic_name__ :List[str] , __magic_name__ :List[Any]=13 , __magic_name__ :Any=7 , __magic_name__ :Optional[int]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :Any=99 , __magic_name__ :List[str]=32 , __magic_name__ :List[str]=5 , __magic_name__ :str=4 , __magic_name__ :str=37 , __magic_name__ :Optional[int]="gelu" , __magic_name__ :int=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Tuple=16 , __magic_name__ :Tuple=2 , __magic_name__ :List[str]=0.02 , __magic_name__ :Any=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = FlaxRoFormerModelTester(self ) @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) a = jnp.array([[0, 1, 2, 3, 4, 5]] ) a = model(__magic_name__ )[0] a = 5_0000 a = (1, 6, vocab_size) self.assertEqual(output.shape , __magic_name__ ) a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
class __lowerCAmelCase : def __init__( self :Union[str, Any] ): '''simple docstring''' a = 0 a = 0 a = {} def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Any ): '''simple docstring''' if vertex not in self.adjacency: a = {} self.num_vertices += 1 def lowerCamelCase__ ( self :Any , __magic_name__ :Dict , __magic_name__ :Union[str, Any] , __magic_name__ :Tuple ): '''simple docstring''' self.add_vertex(__magic_name__ ) self.add_vertex(__magic_name__ ) if head == tail: return a = weight a = weight def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_edges() for edge in edges: a , a , a = edge edges.remove((tail, head, weight) ) for i in range(len(__magic_name__ ) ): a = list(edges[i] ) edges.sort(key=lambda __magic_name__ : e[2] ) for i in range(len(__magic_name__ ) - 1 ): if edges[i][2] >= edges[i + 1][2]: a = edges[i][2] + 1 for edge in edges: a , a , a = edge a = weight a = weight def __str__( self :str ): '''simple docstring''' a = """""" for tail in self.adjacency: for head in self.adjacency[tail]: a = self.adjacency[head][tail] string += F'{head} -> {tail} == {weight}\n' return string.rstrip("""\n""" ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' return self.adjacency.keys() @staticmethod def lowerCamelCase__ ( __magic_name__ :List[str]=None , __magic_name__ :int=None ): '''simple docstring''' a = Graph() if vertices is None: a = [] if edges is None: a = [] for vertex in vertices: g.add_vertex(__magic_name__ ) for edge in edges: g.add_edge(*__magic_name__ ) return g class __lowerCAmelCase : def __init__( self :Optional[int] ): '''simple docstring''' a = {} a = {} def __len__( self :Dict ): '''simple docstring''' return len(self.parent ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :List[str] ): '''simple docstring''' if item in self.parent: return self.find(__magic_name__ ) a = item a = 0 return item def lowerCamelCase__ ( self :List[Any] , __magic_name__ :str ): '''simple docstring''' if item not in self.parent: return self.make_set(__magic_name__ ) if item != self.parent[item]: a = self.find(self.parent[item] ) return self.parent[item] def lowerCamelCase__ ( self :Any , __magic_name__ :Dict , __magic_name__ :Dict ): '''simple docstring''' a = self.find(__magic_name__ ) a = self.find(__magic_name__ ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: a = roota return roota if self.rank[roota] < self.rank[roota]: a = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 a = roota return roota return None @staticmethod def lowerCamelCase__ ( __magic_name__ :Dict ): '''simple docstring''' a = graph.num_vertices a = Graph.UnionFind() a = [] while num_components > 1: a = {} for vertex in graph.get_vertices(): a = -1 a = graph.get_edges() for edge in edges: a , a , a = edge edges.remove((tail, head, weight) ) for edge in edges: a , a , a = edge a = union_find.find(__magic_name__ ) a = union_find.find(__magic_name__ ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: a = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: a = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: a , a , a = cheap_edge[vertex] if union_find.find(__magic_name__ ) != union_find.find(__magic_name__ ): union_find.union(__magic_name__ , __magic_name__ ) mst_edges.append(cheap_edge[vertex] ) a = num_components - 1 a = Graph.build(edges=__magic_name__ ) return mst
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
from __future__ import annotations __UpperCamelCase : List[str] = tuple[int, int, int] __UpperCamelCase : Optional[Any] = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __UpperCamelCase : Optional[Any] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # -------------------------- default selection -------------------------- # rotors -------------------------- __UpperCamelCase : int = "EGZWVONAHDCLFQMSIPJBYUKXTR" __UpperCamelCase : List[Any] = "FOBHMDKEXQNRAULPGSJVTYICZW" __UpperCamelCase : Dict = "ZJXESIUQLHAVRMDOYGTNFWPBKC" # reflector -------------------------- __UpperCamelCase : str = { "A": "N", "N": "A", "B": "O", "O": "B", "C": "P", "P": "C", "D": "Q", "Q": "D", "E": "R", "R": "E", "F": "S", "S": "F", "G": "T", "T": "G", "H": "U", "U": "H", "I": "V", "V": "I", "J": "W", "W": "J", "K": "X", "X": "K", "L": "Y", "Y": "L", "M": "Z", "Z": "M", } # -------------------------- extra rotors -------------------------- __UpperCamelCase : Optional[int] = "RMDJXFUWGISLHVTCQNKYPBEZOA" __UpperCamelCase : Dict = "SGLCPQWZHKXAREONTFBVIYJUDM" __UpperCamelCase : Optional[Any] = "HVSICLTYKQUBXDWAJZOMFGPREN" __UpperCamelCase : List[Any] = "RZWQHFMVDBKICJLNTUXAGYPSOE" __UpperCamelCase : Optional[Any] = "LFKIJODBEGAMQPXVUHYSTCZRWN" __UpperCamelCase : Optional[Any] = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(__lowerCamelCase ) )) < 3: a = f'Please use 3 unique rotors (not {unique_rotsel})' raise Exception(__lowerCamelCase ) # Checks if rotor positions are valid a , a , a = rotpos if not 0 < rotorposa <= len(__lowerCamelCase ): a = f'First rotor position is not within range of 1..26 ({rotorposa}' raise ValueError(__lowerCamelCase ) if not 0 < rotorposa <= len(__lowerCamelCase ): a = f'Second rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(__lowerCamelCase ) if not 0 < rotorposa <= len(__lowerCamelCase ): a = f'Third rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(__lowerCamelCase ) # Validates string and returns dict a = _plugboard(__lowerCamelCase ) return rotpos, rotsel, pbdict def __A ( __lowerCamelCase ) -> dict[str, str]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(__lowerCamelCase , __lowerCamelCase ): a = f'Plugboard setting isn\'t type string ({type(__lowerCamelCase )})' raise TypeError(__lowerCamelCase ) elif len(__lowerCamelCase ) % 2 != 0: a = f'Odd number of symbols ({len(__lowerCamelCase )})' raise Exception(__lowerCamelCase ) elif pbstring == "": return {} pbstring.replace(""" """ , """""" ) # Checks if all characters are unique a = set() for i in pbstring: if i not in abc: a = f'\'{i}\' not in list of symbols' raise Exception(__lowerCamelCase ) elif i in tmppbl: a = f'Duplicate symbol ({i})' raise Exception(__lowerCamelCase ) else: tmppbl.add(__lowerCamelCase ) del tmppbl # Created the dictionary a = {} for j in range(0 , len(__lowerCamelCase ) - 1 , 2 ): a = pbstring[j + 1] a = pbstring[j] return pb def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = (rotora, rotora, rotora) , __lowerCamelCase = "" , ) -> str: a = text.upper() a , a , a = _validator( __lowerCamelCase , __lowerCamelCase , plugb.upper() ) a , a , a = rotor_position a , a , a = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 a = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: a = plugboard[symbol] # rotor ra -------------------------- a = abc.index(__lowerCamelCase ) + rotorposa a = rotora[index % len(__lowerCamelCase )] # rotor rb -------------------------- a = abc.index(__lowerCamelCase ) + rotorposa a = rotora[index % len(__lowerCamelCase )] # rotor rc -------------------------- a = abc.index(__lowerCamelCase ) + rotorposa a = rotora[index % len(__lowerCamelCase )] # reflector -------------------------- # this is the reason you don't need another machine to decipher a = reflector[symbol] # 2nd rotors a = abc[rotora.index(__lowerCamelCase ) - rotorposa] a = abc[rotora.index(__lowerCamelCase ) - rotorposa] a = abc[rotora.index(__lowerCamelCase ) - rotorposa] # 2nd plugboard if symbol in plugboard: a = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(__lowerCamelCase ): a = 0 rotorposa += 1 if rotorposa >= len(__lowerCamelCase ): a = 0 rotorposa += 1 if rotorposa >= len(__lowerCamelCase ): a = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) if __name__ == "__main__": __UpperCamelCase : List[Any] = "This is my Python script that emulates the Enigma machine from WWII." __UpperCamelCase : Union[str, Any] = (1, 1, 1) __UpperCamelCase : List[Any] = "pictures" __UpperCamelCase : Tuple = (rotora, rotora, rotora) __UpperCamelCase : str = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
347
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = (IPNDMScheduler,) UpperCamelCase__ = (('''num_inference_steps''', 50),) def lowerCamelCase__ ( self :Any , **__magic_name__ :Optional[Any] ): '''simple docstring''' a = {"""num_train_timesteps""": 1000} config.update(**__magic_name__ ) return config def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple=0 , **__magic_name__ :Optional[int] ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] , __magic_name__ :List[Any]=0 , **__magic_name__ :Any ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals (must be after setting timesteps) a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) # copy over dummy past residuals new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residual (must be after setting timesteps) a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Optional[Any] , **__magic_name__ :Optional[int] ): '''simple docstring''' a = self.scheduler_classes[0] a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) a = 10 a = self.dummy_model() a = self.dummy_sample_deter scheduler.set_timesteps(__magic_name__ ) for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample return sample def lowerCamelCase__ ( self :str ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) a = self.dummy_sample a = 0.1 * sample if num_inference_steps is not None and hasattr(__magic_name__ , """set_timesteps""" ): scheduler.set_timesteps(__magic_name__ ) elif num_inference_steps is not None and not hasattr(__magic_name__ , """set_timesteps""" ): a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] a = dummy_past_residuals[:] a = scheduler.timesteps[5] a = scheduler.timesteps[6] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.full_loop() a = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_mean.item() - 254_0529 ) < 10
347
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''dandelin/vilt-b32-finetuned-vqa''' UpperCamelCase__ = ( '''This is a tool that answers a question about an image. It takes an input named `image` which should be the ''' '''image containing the information, as well as a `question` which should be the question in English. It ''' '''returns a text that is the answer to the question.''' ) UpperCamelCase__ = '''image_qa''' UpperCamelCase__ = AutoProcessor UpperCamelCase__ = AutoModelForVisualQuestionAnswering UpperCamelCase__ = ['''image''', '''text'''] UpperCamelCase__ = ['''text'''] def __init__( self :Optional[Any] , *__magic_name__ :Any , **__magic_name__ :Tuple ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :"Image" , __magic_name__ :str ): '''simple docstring''' return self.pre_processor(__magic_name__ , __magic_name__ , return_tensors="""pt""" ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Optional[int] ): '''simple docstring''' with torch.no_grad(): return self.model(**__magic_name__ ).logits def lowerCamelCase__ ( self :Dict , __magic_name__ :List[Any] ): '''simple docstring''' a = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
347
__UpperCamelCase : Dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __A ( ) -> None: a = input("""Enter message: """ ) a = input("""Enter key [alphanumeric]: """ ) a = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): a = """encrypt""" a = encrypt_message(__lowerCamelCase , __lowerCamelCase ) elif mode.lower().startswith("""d""" ): a = """decrypt""" a = decrypt_message(__lowerCamelCase , __lowerCamelCase ) print(f'\n{mode.title()}ed message:' ) print(__lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """encrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """decrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: a = [] a = 0 a = key.upper() for symbol in message: a = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__lowerCamelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__lowerCamelCase ): a = 0 else: translated.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) if __name__ == "__main__": main()
347
1
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin __UpperCamelCase : Dict = get_tests_dir("fixtures/test_sentencepiece_bpe.model") class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = BartphoTokenizer UpperCamelCase__ = False UpperCamelCase__ = True def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' super().setUp() a = ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] a = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) a = {"""unk_token""": """<unk>"""} a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""monolingual_vocab_file"""] ) with open(self.monolingual_vocab_file , """w""" , encoding="""utf-8""" ) as fp: for token in vocab_tokens: fp.write(F'{token} {vocab_tokens[token]}\n' ) a = BartphoTokenizer(__magic_name__ , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self :Optional[int] , **__magic_name__ :List[str] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :Union[str, Any] ): '''simple docstring''' a = """This is a là test""" a = """This is a<unk><unk> test""" return input_text, output_text def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = BartphoTokenizer(__magic_name__ , self.monolingual_vocab_file , **self.special_tokens_map ) a = """This is a là test""" a = """▁This ▁is ▁a ▁l à ▁t est""".split() a = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) a = tokens + [tokenizer.unk_token] a = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ )
347
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Tuple=13 , __magic_name__ :List[Any]=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :List[str]=True , __magic_name__ :str=99 , __magic_name__ :Optional[Any]=32 , __magic_name__ :Union[str, Any]=5 , __magic_name__ :Any=4 , __magic_name__ :int=37 , __magic_name__ :Tuple="gelu" , __magic_name__ :List[str]=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :Tuple=512 , __magic_name__ :Dict=16 , __magic_name__ :Optional[int]=2 , __magic_name__ :Optional[int]=0.02 , __magic_name__ :Optional[Any]=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :int ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = True a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = FlaxRobertaModelTester(self ) @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""roberta-base""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ )
347
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : Optional[int] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "adapter_layer": "encoder.layers.*.adapter_layer", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", "pooling_layer.linear": "projector", "pooling_layer.projection": "classifier", } __UpperCamelCase : Dict = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "projector", "classifier", ] def __A ( __lowerCamelCase ) -> Optional[int]: a = {} with open(__lowerCamelCase , """r""" ) as file: for line_number, line in enumerate(__lowerCamelCase ): a = line.strip() if line: a = line.split() a = line_number a = words[0] a = value return result def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: for attribute in key.split(""".""" ): a = getattr(__lowerCamelCase , __lowerCamelCase ) a = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__lowerCamelCase ): a = PARAM_MAPPING[full_name.split(""".""" )[-1]] a = """param""" if weight_type is not None and weight_type != "param": a = getattr(__lowerCamelCase , __lowerCamelCase ).shape elif weight_type is not None and weight_type == "param": a = hf_pointer for attribute in hf_param_name.split(""".""" ): a = getattr(__lowerCamelCase , __lowerCamelCase ) a = shape_pointer.shape # let's reduce dimension a = value[0] else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value elif weight_type == "param": for attribute in hf_param_name.split(""".""" ): a = getattr(__lowerCamelCase , __lowerCamelCase ) a = value else: a = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: a = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__lowerCamelCase ): a = PARAM_MAPPING[full_name.split(""".""" )[-1]] a = """param""" if weight_type is not None and weight_type != "param": a = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": a = """.""".join([key, hf_param_name] ) else: a = key a = value if """lm_head""" in full_key else value[0] __UpperCamelCase : int = { "W_a": "linear_1.weight", "W_b": "linear_2.weight", "b_a": "linear_1.bias", "b_b": "linear_2.bias", "ln_W": "norm.weight", "ln_b": "norm.bias", } def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None ) -> Dict: a = False for key, mapped_key in MAPPING.items(): a = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: a = True if "*" in mapped_key: a = name.split(__lowerCamelCase )[0].split(""".""" )[-2] a = mapped_key.replace("""*""" , __lowerCamelCase ) if "weight_g" in name: a = """weight_g""" elif "weight_v" in name: a = """weight_v""" elif "bias" in name: a = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj a = """weight""" else: a = None if hf_dict is not None: rename_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) else: set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return is_used return is_used def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: a = [] a = fairseq_model.state_dict() a = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) a = True else: a = load_wavaveca_layer(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(f'Unused weights: {unused_weights}' ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: a = full_name.split("""conv_layers.""" )[-1] a = name.split(""".""" ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) a = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) a = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.' ) a = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.' ) a = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) @torch.no_grad() def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=True , __lowerCamelCase=False ) -> List[Any]: if config_path is not None: a = WavaVecaConfig.from_pretrained(__lowerCamelCase ) else: a = WavaVecaConfig() if is_seq_class: a = read_txt_into_dict(__lowerCamelCase ) a = idalabel a = WavaVecaForSequenceClassification(__lowerCamelCase ) a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) feature_extractor.save_pretrained(__lowerCamelCase ) elif is_finetuned: if dict_path: a = Dictionary.load(__lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq a = target_dict.pad_index a = target_dict.bos_index a = target_dict.eos_index a = len(target_dict.symbols ) a = os.path.join(__lowerCamelCase , """vocab.json""" ) if not os.path.isdir(__lowerCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__lowerCamelCase ) ) return os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) a = target_dict.indices # fairseq has the <pad> and <s> switched a = 0 a = 1 with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(__lowerCamelCase , __lowerCamelCase ) a = WavaVecaCTCTokenizer( __lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=__lowerCamelCase , ) a = True if config.feat_extract_norm == """layer""" else False a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) a = WavaVecaProcessor(feature_extractor=__lowerCamelCase , tokenizer=__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) a = WavaVecaForCTC(__lowerCamelCase ) else: a = WavaVecaForPreTraining(__lowerCamelCase ) if is_finetuned or is_seq_class: a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: a = argparse.Namespace(task="""audio_pretraining""" ) a = fairseq.tasks.setup_task(__lowerCamelCase ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__lowerCamelCase ) a = model[0].eval() recursively_load_weights(__lowerCamelCase , __lowerCamelCase , not is_finetuned ) hf_wavavec.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": __UpperCamelCase : List[Any] = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) parser.add_argument( "--is_seq_class", action="store_true", help="Whether the model to convert is a fine-tuned sequence classification model or not", ) __UpperCamelCase : Tuple = parser.parse_args() __UpperCamelCase : Optional[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
347
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __UpperCamelCase : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): UpperCamelCase__ = None UpperCamelCase__ = "utf-8" UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = True # deprecated UpperCamelCase__ = None # deprecated UpperCamelCase__ = 10 << 20 # 10MB UpperCamelCase__ = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): UpperCamelCase__ = JsonConfig def lowerCamelCase__ ( self :str ): '''simple docstring''' if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) a = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__magic_name__ , (str, list, tuple) ): a = data_files if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] a = [] for split_name, files in data_files.items(): if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] splits.append(datasets.SplitGenerator(name=__magic_name__ , gen_kwargs={"""files""": files} ) ) return splits def lowerCamelCase__ ( self :List[str] , __magic_name__ :pa.Table ): '''simple docstring''' if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): a = self.config.features.arrow_schema.field(__magic_name__ ).type a = pa_table.append_column(__magic_name__ , pa.array([None] * len(__magic_name__ ) , type=__magic_name__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example a = table_cast(__magic_name__ , self.config.features.arrow_schema ) return pa_table def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Union[str, Any] ): '''simple docstring''' for file_idx, file in enumerate(itertools.chain.from_iterable(__magic_name__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) # We keep only the field we are interested in a = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__magic_name__ , (list, tuple) ): a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} else: a = dataset a = pa.Table.from_pydict(__magic_name__ ) yield file_idx, self._cast_table(__magic_name__ ) # If the file has one json object per line else: with open(__magic_name__ , """rb""" ) as f: a = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small a = max(self.config.chunksize // 32 , 16 << 10 ) a = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: a = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__magic_name__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": a = batch.decode(self.config.encoding , errors=__magic_name__ ).encode("""utf-8""" ) try: while True: try: a = paj.read_json( io.BytesIO(__magic_name__ ) , read_options=paj.ReadOptions(block_size=__magic_name__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__magic_name__ , pa.ArrowInvalid ) and "straddling" not in str(__magic_name__ ) or block_size > len(__magic_name__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F'Batch of {len(__magic_name__ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( __magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) except json.JSONDecodeError: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__magic_name__ , __magic_name__ ): # list is the only sequence type supported in JSON try: a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} a = pa.Table.from_pydict(__magic_name__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError(F'Not able to read records in the JSON file at {file}.' ) from None yield file_idx, self._cast_table(__magic_name__ ) break else: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError( F'Not able to read records in the JSON file at {file}. ' F'You should probably indicate the field of the JSON file containing your records. ' F'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ' F'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__magic_name__ ) batch_idx += 1
347
1
from __future__ import annotations def __A ( __lowerCamelCase , __lowerCamelCase ) -> bool: a = get_failure_array(__lowerCamelCase ) # 2) Step through text searching for pattern a , a = 0, 0 # index into text, pattern while i < len(__lowerCamelCase ): if pattern[j] == text[i]: if j == (len(__lowerCamelCase ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: a = failure[j - 1] continue i += 1 return False def __A ( __lowerCamelCase ) -> list[int]: a = [0] a = 0 a = 1 while j < len(__lowerCamelCase ): if pattern[i] == pattern[j]: i += 1 elif i > 0: a = failure[i - 1] continue j += 1 failure.append(__lowerCamelCase ) return failure if __name__ == "__main__": # Test 1) __UpperCamelCase : List[Any] = "abc1abc12" __UpperCamelCase : Tuple = "alskfjaldsabc1abc1abc12k23adsfabcabc" __UpperCamelCase : int = "alskfjaldsk23adsfabcabc" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) __UpperCamelCase : Dict = "ABABX" __UpperCamelCase : int = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) __UpperCamelCase : Dict = "AAAB" __UpperCamelCase : List[str] = "ABAAAAAB" assert kmp(pattern, text) # Test 4) __UpperCamelCase : Union[str, Any] = "abcdabcy" __UpperCamelCase : str = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) __UpperCamelCase : Tuple = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
347
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :List[str] , __magic_name__ :int="</s>" , __magic_name__ :List[Any]="<unk>" , __magic_name__ :Optional[Any]="<pad>" , __magic_name__ :Optional[int]=125 , __magic_name__ :List[str]=None , **__magic_name__ :List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: a = [F'<extra_id_{i}>' for i in range(__magic_name__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens a = len(set(filter(lambda __magic_name__ : bool("""extra_id""" in str(__magic_name__ ) ) , __magic_name__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to ByT5Tokenizer. In this case the additional_special_tokens must include the""" """ extra_ids tokens""" ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token super().__init__( eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , extra_ids=__magic_name__ , additional_special_tokens=__magic_name__ , **__magic_name__ , ) a = extra_ids a = 2**8 # utf is 8 bits # define special tokens dict a = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } a = len(self.special_tokens_encoder ) a = len(__magic_name__ ) for i, token in enumerate(__magic_name__ ): a = self.vocab_size + i - n a = {v: k for k, v in self.special_tokens_encoder.items()} @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def lowerCamelCase__ ( self :Any , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None , __magic_name__ :bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__magic_name__ )) + [1] return ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def lowerCamelCase__ ( self :str , __magic_name__ :List[int] ): '''simple docstring''' if len(__magic_name__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = self._add_eos_if_not_present(__magic_name__ ) if token_ids_a is None: return token_ids_a else: a = self._add_eos_if_not_present(__magic_name__ ) return token_ids_a + token_ids_a def lowerCamelCase__ ( self :List[str] , __magic_name__ :str ): '''simple docstring''' a = [chr(__magic_name__ ) for i in text.encode("""utf-8""" )] return tokens def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if token in self.special_tokens_encoder: a = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: a = self.added_tokens_encoder[token] elif len(__magic_name__ ) != 1: a = self.unk_token_id else: a = ord(__magic_name__ ) + self._num_special_tokens return token_id def lowerCamelCase__ ( self :List[str] , __magic_name__ :Dict ): '''simple docstring''' if index in self.special_tokens_decoder: a = self.special_tokens_decoder[index] else: a = chr(index - self._num_special_tokens ) return token def lowerCamelCase__ ( self :Tuple , __magic_name__ :Optional[int] ): '''simple docstring''' a = b"""""" for token in tokens: if token in self.special_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.added_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.special_tokens_encoder: a = token.encode("""utf-8""" ) elif token in self.added_tokens_encoder: a = token.encode("""utf-8""" ) else: a = bytes([ord(__magic_name__ )] ) bstring += tok_string a = bstring.decode("""utf-8""" , errors="""ignore""" ) return string def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :str , __magic_name__ :Optional[str] = None ): '''simple docstring''' return ()
347
1
from __future__ import annotations __UpperCamelCase : Any = "#" class __lowerCAmelCase : def __init__( self :str ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' a = self._trie for char in text: if char not in trie: a = {} a = trie[char] a = True def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' a = self._trie for char in prefix: if char in trie: a = trie[char] else: return [] return self._elements(__magic_name__ ) def lowerCamelCase__ ( self :Dict , __magic_name__ :dict ): '''simple docstring''' a = [] for c, v in d.items(): a = [""" """] if c == END else [(c + s) for s in self._elements(__magic_name__ )] result.extend(__magic_name__ ) return tuple(__magic_name__ ) __UpperCamelCase : int = Trie() __UpperCamelCase : Optional[int] = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def __A ( __lowerCamelCase ) -> tuple: a = trie.find_word(__lowerCamelCase ) return tuple(string + word for word in suffixes ) def __A ( ) -> None: print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
347
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __lowerCAmelCase : def __init__( self :Optional[int] , __magic_name__ :str , __magic_name__ :int=2 , __magic_name__ :List[str]=3 , __magic_name__ :Optional[int]=4 , __magic_name__ :str=2 , __magic_name__ :Any=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Dict=True , __magic_name__ :List[Any]=99 , __magic_name__ :Dict=36 , __magic_name__ :Optional[Any]=3 , __magic_name__ :str=4 , __magic_name__ :Optional[Any]=37 , __magic_name__ :Dict="gelu" , __magic_name__ :Any=0.1 , __magic_name__ :Union[str, Any]=0.1 , __magic_name__ :Dict=512 , __magic_name__ :str=16 , __magic_name__ :List[Any]=2 , __magic_name__ :Tuple=0.02 , __magic_name__ :Any=6 , __magic_name__ :Optional[int]=6 , __magic_name__ :Tuple=3 , __magic_name__ :str=4 , __magic_name__ :List[str]=None , __magic_name__ :str=1000 , ): '''simple docstring''' a = parent a = batch_size a = num_channels a = image_size a = patch_size a = text_seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = coordinate_size a = shape_size a = num_labels a = num_choices a = scope a = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) a = text_seq_length a = (image_size // patch_size) ** 2 + 1 a = self.text_seq_length + self.image_seq_length def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) a = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a = bbox[i, j, 3] a = bbox[i, j, 1] a = t if bbox[i, j, 2] < bbox[i, j, 0]: a = bbox[i, j, 2] a = bbox[i, j, 0] a = t a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.text_seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) a = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def lowerCamelCase__ ( self :int , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :List[str] , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int ): '''simple docstring''' a = LayoutLMvaModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # text + image a = model(__magic_name__ , pixel_values=__magic_name__ ) a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only a = model(__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only a = model(pixel_values=__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :List[Any] , __magic_name__ :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Union[str, Any] , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :List[str] , __magic_name__ :List[str] ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Dict , __magic_name__ :Optional[Any] , __magic_name__ :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :int , __magic_name__ :List[str] , __magic_name__ :Tuple ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :str , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :str , __magic_name__ :List[str] , __magic_name__ :Optional[int] , __magic_name__ :Optional[Any] ): '''simple docstring''' a = LayoutLMvaForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase__ = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :Optional[Any] , __magic_name__ :List[str] , __magic_name__ :List[Any] ): '''simple docstring''' return True def lowerCamelCase__ ( self :int ): '''simple docstring''' a = LayoutLMvaModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :Any=False ): '''simple docstring''' a = copy.deepcopy(__magic_name__ ) if model_class in get_values(__magic_name__ ): a = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__magic_name__ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__magic_name__ ): a = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in get_values(__magic_name__ ): a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__magic_name__ , ) return inputs_dict def lowerCamelCase__ ( self :str ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a = type self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def lowerCamelCase__ ( self :int ): '''simple docstring''' for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = LayoutLMvaModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def __A ( ) -> str: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__magic_name__ ) if is_vision_available() else None @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(__magic_name__ ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__magic_name__ , return_tensors="""pt""" ).pixel_values.to(__magic_name__ ) a = torch.tensor([[1, 2]] ) a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass a = model( input_ids=input_ids.to(__magic_name__ ) , bbox=bbox.to(__magic_name__ ) , pixel_values=pixel_values.to(__magic_name__ ) , ) # verify the logits a = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __magic_name__ ) a = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
from __future__ import annotations from PIL import Image # Define glider example __UpperCamelCase : List[Any] = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example __UpperCamelCase : str = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def __A ( __lowerCamelCase ) -> list[list[int]]: a = [] for i in range(len(__lowerCamelCase ) ): a = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours a = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(__lowerCamelCase ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(__lowerCamelCase ) - 1: neighbour_count += cells[i + 1][j] if i < len(__lowerCamelCase ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. a = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(__lowerCamelCase ) return next_generation def __A ( __lowerCamelCase , __lowerCamelCase ) -> list[Image.Image]: a = [] for _ in range(__lowerCamelCase ): # Create output image a = Image.new("""RGB""" , (len(cells[0] ), len(__lowerCamelCase )) ) a = img.load() # Save cells to image for x in range(len(__lowerCamelCase ) ): for y in range(len(cells[0] ) ): a = 255 - cells[y][x] * 255 a = (colour, colour, colour) # Save image images.append(__lowerCamelCase ) a = new_generation(__lowerCamelCase ) return images if __name__ == "__main__": __UpperCamelCase : Any = generate_images(GLIDER, 16) images[0].save("out.gif", save_all=True, append_images=images[1:])
347
from copy import deepcopy class __lowerCAmelCase : def __init__( self :Union[str, Any] , __magic_name__ :list[int] | None = None , __magic_name__ :int | None = None ): '''simple docstring''' if arr is None and size is not None: a = size a = [0] * size elif arr is not None: self.init(__magic_name__ ) else: raise ValueError("""Either arr or size must be specified""" ) def lowerCamelCase__ ( self :Dict , __magic_name__ :list[int] ): '''simple docstring''' a = len(__magic_name__ ) a = deepcopy(__magic_name__ ) for i in range(1 , self.size ): a = self.next_(__magic_name__ ) if j < self.size: self.tree[j] += self.tree[i] def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): a = self.next_(__magic_name__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index + (index & (-index)) @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index - (index & (-index)) def lowerCamelCase__ ( self :Any , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value a = self.next_(__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' self.add(__magic_name__ , value - self.get(__magic_name__ ) ) def lowerCamelCase__ ( self :int , __magic_name__ :int ): '''simple docstring''' if right == 0: return 0 a = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] a = self.prev(__magic_name__ ) return result def lowerCamelCase__ ( self :int , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' return self.prefix(__magic_name__ ) - self.prefix(__magic_name__ ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :int ): '''simple docstring''' return self.query(__magic_name__ , index + 1 ) def lowerCamelCase__ ( self :Dict , __magic_name__ :int ): '''simple docstring''' value -= self.tree[0] if value < 0: return -1 a = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 a = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
347
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __UpperCamelCase : List[Any] = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") __UpperCamelCase : int = subprocess.check_output(F'git diff --name-only {fork_point_sha}'.split()).decode("utf-8").split() __UpperCamelCase : str = "|".join(sys.argv[1:]) __UpperCamelCase : int = re.compile(RF'^({joined_dirs}).*?\.py$') __UpperCamelCase : Optional[Any] = [x for x in modified_files if regex.match(x)] print(" ".join(relevant_modified_files), end="")
347
from __future__ import annotations from typing import Generic, TypeVar __UpperCamelCase : Union[str, Any] = TypeVar("T") class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple , __magic_name__ :T ): '''simple docstring''' a = data a = self a = 0 class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T ): '''simple docstring''' a = DisjointSetTreeNode(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :T ): '''simple docstring''' a = self.map[data] if elem_ref != elem_ref.parent: a = self.find_set(elem_ref.parent.data ) return elem_ref.parent def lowerCamelCase__ ( self :List[Any] , __magic_name__ :DisjointSetTreeNode[T] , __magic_name__ :DisjointSetTreeNode[T] ): '''simple docstring''' if nodea.rank > nodea.rank: a = nodea else: a = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T , __magic_name__ :T ): '''simple docstring''' self.link(self.find_set(__magic_name__ ) , self.find_set(__magic_name__ ) ) class __lowerCAmelCase ( Generic[T] ): def __init__( self :Union[str, Any] ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :T ): '''simple docstring''' if node not in self.connections: a = {} def lowerCamelCase__ ( self :Any , __magic_name__ :T , __magic_name__ :T , __magic_name__ :int ): '''simple docstring''' self.add_node(__magic_name__ ) self.add_node(__magic_name__ ) a = weight a = weight def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] a = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda __magic_name__ : x[2] ) # creating the disjoint set a = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__magic_name__ ) # MST generation a = 0 a = 0 a = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: a , a , a = edges[index] index += 1 a = disjoint_set.find_set(__magic_name__ ) a = disjoint_set.find_set(__magic_name__ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__magic_name__ , __magic_name__ , __magic_name__ ) disjoint_set.union(__magic_name__ , __magic_name__ ) return graph
347
1
import math def __A ( __lowerCamelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__lowerCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __A ( __lowerCamelCase = 0.1 ) -> int: a = 3 a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__lowerCamelCase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
347
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = tempfile.mkdtemp() a = BlipImageProcessor() a = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) a = BlipProcessor(__magic_name__ , __magic_name__ ) processor.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self :List[Any] , **__magic_name__ :Union[str, Any] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).tokenizer def lowerCamelCase__ ( self :str , **__magic_name__ :List[str] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).image_processor def lowerCamelCase__ ( self :int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__magic_name__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) a = self.get_image_processor(do_normalize=__magic_name__ , padding_value=1.0 ) a = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__magic_name__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __magic_name__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = self.prepare_image_inputs() a = image_processor(__magic_name__ , return_tensors="""np""" ) a = processor(images=__magic_name__ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = processor(text=__magic_name__ ) a = tokenizer(__magic_name__ , return_token_type_ids=__magic_name__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(__magic_name__ ): processor() def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__magic_name__ ) a = tokenizer.batch_decode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
347
1
from __future__ import annotations def __A ( __lowerCamelCase ) -> list[int]: a = 2 a = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(__lowerCamelCase ) if n > 1: factors.append(__lowerCamelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
347
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : int = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class __lowerCAmelCase ( __magic_name__ , __magic_name__ ): UpperCamelCase__ = '''nat''' UpperCamelCase__ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self :Any , __magic_name__ :int=4 , __magic_name__ :Dict=3 , __magic_name__ :List[str]=64 , __magic_name__ :Optional[int]=[3, 4, 6, 5] , __magic_name__ :int=[2, 4, 8, 16] , __magic_name__ :str=7 , __magic_name__ :Tuple=3.0 , __magic_name__ :Dict=True , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.1 , __magic_name__ :Optional[Any]="gelu" , __magic_name__ :Optional[Any]=0.02 , __magic_name__ :Tuple=1E-5 , __magic_name__ :Union[str, Any]=0.0 , __magic_name__ :int=None , __magic_name__ :Any=None , **__magic_name__ :Dict , ): '''simple docstring''' super().__init__(**__magic_name__ ) a = patch_size a = num_channels a = embed_dim a = depths a = len(__magic_name__ ) a = num_heads a = kernel_size a = mlp_ratio a = qkv_bias a = hidden_dropout_prob a = attention_probs_dropout_prob a = drop_path_rate a = hidden_act a = layer_norm_eps a = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model a = int(embed_dim * 2 ** (len(__magic_name__ ) - 1) ) a = layer_scale_init_value a = ["""stem"""] + [F'stage{idx}' for idx in range(1 , len(__magic_name__ ) + 1 )] a , a = get_aligned_output_features_output_indices( out_features=__magic_name__ , out_indices=__magic_name__ , stage_names=self.stage_names )
347
1
import requests def __A ( __lowerCamelCase , __lowerCamelCase ) -> None: a = {"""Content-Type""": """application/json"""} a = requests.post(__lowerCamelCase , json={"""text""": message_body} , headers=__lowerCamelCase ) if response.status_code != 200: a = ( """Request to slack returned an error """ f'{response.status_code}, the response is:\n{response.text}' ) raise ValueError(__lowerCamelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
347
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer a = flax_key_tuple[:-1] + ("""weight""",) a = torch.permute(__lowerCamelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCamelCase ): # linear layer a = flax_key_tuple[:-1] + ("""weight""",) a = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: a = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: if "metadata" in layer: a = layer.split("""metadata""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: a = layer.split("""kvstore""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: a = layer.split("""/""" ) a = """/""".join(split_layer[:-1] ) a = (split_layer[-1],) if "kvstore/path" in layer: a = f'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: a = """file""" else: a = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __A ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: a = rename_keys(__lowerCamelCase ) a = {} for k, v in current_block.items(): a = v a = new_current_block torch.save(__lowerCamelCase , __lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = WEIGHTS_NAME ) -> List[str]: a = convert_file_size_to_int(__lowerCamelCase ) a = [] a = {} a = 0 a = 0 os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: a = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] a = flatten_dict(__lowerCamelCase , sep="""/""" ) a = {} for layer in checkpoint_info.keys(): a , a , a = get_key_and_tensorstore_dict( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if curr_real_layer_name in all_layers: a = content else: a = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() a = torch.tensor(__lowerCamelCase ) a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts a , a = rename_base_flax_keys(tuple(key.split("""/""" ) ) , __lowerCamelCase ) a = """/""".join(__lowerCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: a = os.path.join( __lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block a = {} a = 0 a = raw_weights.to(getattr(__lowerCamelCase , __lowerCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index a = {} a = {} for idx, shard in enumerate(__lowerCamelCase ): a = weights_name.replace( """.bin""" , f'-{idx+1:05d}-of-{len(__lowerCamelCase ):05d}.bin' ) # len(sharded_state_dicts):05d} a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{idx+1:05d}-of-???.bin' ) ) os.rename(__lowerCamelCase , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) a = shard for key in shard: a = shard_file # Add the metadata a = {"""total_size""": total_size} a = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(__lowerCamelCase , __lowerCamelCase ) , """w""" , encoding="""utf-8""" ) as f: a = json.dumps(__lowerCamelCase , indent=2 , sort_keys=__lowerCamelCase ) + """\n""" f.write(__lowerCamelCase ) return metadata, index if __name__ == "__main__": __UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __UpperCamelCase : Any = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __A ( ) -> Tuple: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer a = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) a = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) a = TaTokenizer.from_pretrained("""t5-small""" ) a = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" a = tokenizer(__lowerCamelCase , return_tensors="""pt""" ).input_ids a = model.generate(__lowerCamelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
347
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = XLMRobertaModel.from_pretrained("""xlm-roberta-base""" ) a = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]] ) # The dog is cute and lives in the garden house a = torch.Size((1, 12, 768) ) # batch_size, sequence_length, embedding_vector_dim a = torch.tensor( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): a = model(__magic_name__ )["""last_hidden_state"""].detach() self.assertEqual(output.shape , __magic_name__ ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __magic_name__ , atol=1E-3 ) ) @slow def lowerCamelCase__ ( self :int ): '''simple docstring''' a = XLMRobertaModel.from_pretrained("""xlm-roberta-large""" ) a = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]] ) # The dog is cute and lives in the garden house a = torch.Size((1, 12, 1024) ) # batch_size, sequence_length, embedding_vector_dim a = torch.tensor( [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): a = model(__magic_name__ )["""last_hidden_state"""].detach() self.assertEqual(output.shape , __magic_name__ ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __magic_name__ , atol=1E-3 ) )
347
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __UpperCamelCase : Union[str, Any] = (720, 1_280) # Height, Width __UpperCamelCase : Any = (0.4, 0.6) # if height or width lower than this scale, drop it. __UpperCamelCase : str = 1 / 100 __UpperCamelCase : Optional[int] = "" __UpperCamelCase : List[Any] = "" __UpperCamelCase : Union[str, Any] = "" __UpperCamelCase : Tuple = 250 def __A ( ) -> None: a , a = get_dataset(__lowerCamelCase , __lowerCamelCase ) for index in range(__lowerCamelCase ): a = random.sample(range(len(__lowerCamelCase ) ) , 4 ) a , a , a = update_image_and_anno( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , filter_scale=__lowerCamelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' a = random_chars(32 ) a = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] a = f'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(f'{file_root}.jpg' , __lowerCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) a = [] for anno in new_annos: a = anno[3] - anno[1] a = anno[4] - anno[2] a = anno[1] + width / 2 a = anno[2] + height / 2 a = f'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(__lowerCamelCase ) with open(f'{file_root}.txt' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> tuple[list, list]: a = [] a = [] for label_file in glob.glob(os.path.join(__lowerCamelCase , """*.txt""" ) ): a = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCamelCase ) as in_file: a = in_file.readlines() a = os.path.join(__lowerCamelCase , f'{label_name}.jpg' ) a = [] for obj_list in obj_lists: a = obj_list.rstrip("""\n""" ).split(""" """ ) a = float(obj[1] ) - float(obj[3] ) / 2 a = float(obj[2] ) - float(obj[4] ) / 2 a = float(obj[1] ) + float(obj[3] ) / 2 a = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__lowerCamelCase ) labels.append(__lowerCamelCase ) return img_paths, labels def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 0.0 , ) -> tuple[list, list, str]: a = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = int(scale_x * output_size[1] ) a = int(scale_y * output_size[0] ) a = [] a = [] for i, index in enumerate(__lowerCamelCase ): a = all_img_list[index] path_list.append(__lowerCamelCase ) a = all_annos[index] a = cva.imread(__lowerCamelCase ) if i == 0: # top-left a = cva.resize(__lowerCamelCase , (divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = bbox[2] * scale_y a = bbox[3] * scale_x a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right a = cva.resize(__lowerCamelCase , (output_size[1] - divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = bbox[2] * scale_y a = scale_x + bbox[3] * (1 - scale_x) a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left a = cva.resize(__lowerCamelCase , (divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = scale_y + bbox[2] * (1 - scale_y) a = bbox[3] * scale_x a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right a = cva.resize( __lowerCamelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = scale_y + bbox[2] * (1 - scale_y) a = scale_x + bbox[3] * (1 - scale_x) a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: a = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __A ( __lowerCamelCase ) -> str: assert number_char > 1, "The number of character should greater than 1" a = ascii_lowercase + digits return "".join(random.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
347
1
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = ['''image_processor''', '''tokenizer'''] UpperCamelCase__ = '''ViltImageProcessor''' UpperCamelCase__ = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self :Optional[int] , __magic_name__ :Any=None , __magic_name__ :List[str]=None , **__magic_name__ :List[Any] ): '''simple docstring''' a = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __magic_name__ , ) a = kwargs.pop("""feature_extractor""" ) a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__magic_name__ , __magic_name__ ) a = self.image_processor def __call__( self :Tuple , __magic_name__ :Union[str, Any] , __magic_name__ :Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __magic_name__ :bool = True , __magic_name__ :Union[bool, str, PaddingStrategy] = False , __magic_name__ :Union[bool, str, TruncationStrategy] = None , __magic_name__ :Optional[int] = None , __magic_name__ :int = 0 , __magic_name__ :Optional[int] = None , __magic_name__ :Optional[bool] = None , __magic_name__ :Optional[bool] = None , __magic_name__ :bool = False , __magic_name__ :bool = False , __magic_name__ :bool = False , __magic_name__ :bool = False , __magic_name__ :bool = True , __magic_name__ :Optional[Union[str, TensorType]] = None , **__magic_name__ :Dict , ): '''simple docstring''' a = self.tokenizer( text=__magic_name__ , add_special_tokens=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , max_length=__magic_name__ , stride=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_token_type_ids=__magic_name__ , return_attention_mask=__magic_name__ , return_overflowing_tokens=__magic_name__ , return_special_tokens_mask=__magic_name__ , return_offsets_mapping=__magic_name__ , return_length=__magic_name__ , verbose=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ , ) # add pixel_values + pixel_mask a = self.image_processor(__magic_name__ , return_tensors=__magic_name__ ) encoding.update(__magic_name__ ) return encoding def lowerCamelCase__ ( self :List[str] , *__magic_name__ :Dict , **__magic_name__ :int ): '''simple docstring''' return self.tokenizer.batch_decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] , *__magic_name__ :Optional[int] , **__magic_name__ :Optional[int] ): '''simple docstring''' return self.tokenizer.decode(*__magic_name__ , **__magic_name__ ) @property def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.tokenizer.model_input_names a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __magic_name__ , ) return self.image_processor_class @property def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __magic_name__ , ) return self.image_processor
347
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Optional[Any] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "MobileNetV2OnnxConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ["MobileNetV2FeatureExtractor"] __UpperCamelCase : Tuple = ["MobileNetV2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV2ForImageClassification", "MobileNetV2ForSemanticSegmentation", "MobileNetV2Model", "MobileNetV2PreTrainedModel", "load_tf_weights_in_mobilenet_v2", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
__UpperCamelCase : Union[str, Any] = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def __A ( __lowerCamelCase ) -> str: assert type(__lowerCamelCase ) in (int, float) and decimal == int(__lowerCamelCase ) a = int(__lowerCamelCase ) a = """""" a = False if decimal < 0: a = True decimal *= -1 while decimal > 0: a , a = divmod(__lowerCamelCase , 16 ) a = values[remainder] + hexadecimal a = """0x""" + hexadecimal if negative: a = """-""" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
347
def __A ( __lowerCamelCase ) -> bool: if num < 0: return False a = num a = 0 while num > 0: a = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
1
import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() __UpperCamelCase : int = logging.get_logger("transformers.models.encodec") __UpperCamelCase : Optional[int] = { "quantizer.vq.layers.*._codebook.inited": "quantizer.layers.*.codebook.inited", "quantizer.vq.layers.*._codebook.cluster_size": "quantizer.layers.*.codebook.cluster_size", "quantizer.vq.layers.*._codebook.embed": "quantizer.layers.*.codebook.embed", "quantizer.vq.layers.*._codebook.embed_avg": "quantizer.layers.*.codebook.embed_avg", } __UpperCamelCase : Tuple = { "encoder.model.0.conv.conv": "encoder.layers.0.conv", "encoder.model.1.block.1.conv.conv": "encoder.layers.1.block.1.conv", "encoder.model.1.block.3.conv.conv": "encoder.layers.1.block.3.conv", "encoder.model.1.shortcut.conv.conv": "encoder.layers.1.shortcut.conv", "encoder.model.3.conv.conv": "encoder.layers.3.conv", "encoder.model.4.block.1.conv.conv": "encoder.layers.4.block.1.conv", "encoder.model.4.block.3.conv.conv": "encoder.layers.4.block.3.conv", "encoder.model.4.shortcut.conv.conv": "encoder.layers.4.shortcut.conv", "encoder.model.6.conv.conv": "encoder.layers.6.conv", "encoder.model.7.block.1.conv.conv": "encoder.layers.7.block.1.conv", "encoder.model.7.block.3.conv.conv": "encoder.layers.7.block.3.conv", "encoder.model.7.shortcut.conv.conv": "encoder.layers.7.shortcut.conv", "encoder.model.9.conv.conv": "encoder.layers.9.conv", "encoder.model.10.block.1.conv.conv": "encoder.layers.10.block.1.conv", "encoder.model.10.block.3.conv.conv": "encoder.layers.10.block.3.conv", "encoder.model.10.shortcut.conv.conv": "encoder.layers.10.shortcut.conv", "encoder.model.12.conv.conv": "encoder.layers.12.conv", "encoder.model.13.lstm": "encoder.layers.13.lstm", "encoder.model.15.conv.conv": "encoder.layers.15.conv", } __UpperCamelCase : Optional[Any] = { "encoder.model.0.conv.norm": "encoder.layers.0.norm", "encoder.model.1.block.1.conv.norm": "encoder.layers.1.block.1.norm", "encoder.model.1.block.3.conv.norm": "encoder.layers.1.block.3.norm", "encoder.model.1.shortcut.conv.norm": "encoder.layers.1.shortcut.norm", "encoder.model.3.conv.norm": "encoder.layers.3.norm", "encoder.model.4.block.1.conv.norm": "encoder.layers.4.block.1.norm", "encoder.model.4.block.3.conv.norm": "encoder.layers.4.block.3.norm", "encoder.model.4.shortcut.conv.norm": "encoder.layers.4.shortcut.norm", "encoder.model.6.conv.norm": "encoder.layers.6.norm", "encoder.model.7.block.1.conv.norm": "encoder.layers.7.block.1.norm", "encoder.model.7.block.3.conv.norm": "encoder.layers.7.block.3.norm", "encoder.model.7.shortcut.conv.norm": "encoder.layers.7.shortcut.norm", "encoder.model.9.conv.norm": "encoder.layers.9.norm", "encoder.model.10.block.1.conv.norm": "encoder.layers.10.block.1.norm", "encoder.model.10.block.3.conv.norm": "encoder.layers.10.block.3.norm", "encoder.model.10.shortcut.conv.norm": "encoder.layers.10.shortcut.norm", "encoder.model.12.conv.norm": "encoder.layers.12.norm", "encoder.model.15.conv.norm": "encoder.layers.15.norm", } __UpperCamelCase : Optional[int] = { "decoder.model.0.conv.conv": "decoder.layers.0.conv", "decoder.model.1.lstm": "decoder.layers.1.lstm", "decoder.model.3.convtr.convtr": "decoder.layers.3.conv", "decoder.model.4.block.1.conv.conv": "decoder.layers.4.block.1.conv", "decoder.model.4.block.3.conv.conv": "decoder.layers.4.block.3.conv", "decoder.model.4.shortcut.conv.conv": "decoder.layers.4.shortcut.conv", "decoder.model.6.convtr.convtr": "decoder.layers.6.conv", "decoder.model.7.block.1.conv.conv": "decoder.layers.7.block.1.conv", "decoder.model.7.block.3.conv.conv": "decoder.layers.7.block.3.conv", "decoder.model.7.shortcut.conv.conv": "decoder.layers.7.shortcut.conv", "decoder.model.9.convtr.convtr": "decoder.layers.9.conv", "decoder.model.10.block.1.conv.conv": "decoder.layers.10.block.1.conv", "decoder.model.10.block.3.conv.conv": "decoder.layers.10.block.3.conv", "decoder.model.10.shortcut.conv.conv": "decoder.layers.10.shortcut.conv", "decoder.model.12.convtr.convtr": "decoder.layers.12.conv", "decoder.model.13.block.1.conv.conv": "decoder.layers.13.block.1.conv", "decoder.model.13.block.3.conv.conv": "decoder.layers.13.block.3.conv", "decoder.model.13.shortcut.conv.conv": "decoder.layers.13.shortcut.conv", "decoder.model.15.conv.conv": "decoder.layers.15.conv", } __UpperCamelCase : Dict = { "decoder.model.0.conv.norm": "decoder.layers.0.norm", "decoder.model.3.convtr.norm": "decoder.layers.3.norm", "decoder.model.4.block.1.conv.norm": "decoder.layers.4.block.1.norm", "decoder.model.4.block.3.conv.norm": "decoder.layers.4.block.3.norm", "decoder.model.4.shortcut.conv.norm": "decoder.layers.4.shortcut.norm", "decoder.model.6.convtr.norm": "decoder.layers.6.norm", "decoder.model.7.block.1.conv.norm": "decoder.layers.7.block.1.norm", "decoder.model.7.block.3.conv.norm": "decoder.layers.7.block.3.norm", "decoder.model.7.shortcut.conv.norm": "decoder.layers.7.shortcut.norm", "decoder.model.9.convtr.norm": "decoder.layers.9.norm", "decoder.model.10.block.1.conv.norm": "decoder.layers.10.block.1.norm", "decoder.model.10.block.3.conv.norm": "decoder.layers.10.block.3.norm", "decoder.model.10.shortcut.conv.norm": "decoder.layers.10.shortcut.norm", "decoder.model.12.convtr.norm": "decoder.layers.12.norm", "decoder.model.13.block.1.conv.norm": "decoder.layers.13.block.1.norm", "decoder.model.13.block.3.conv.norm": "decoder.layers.13.block.3.norm", "decoder.model.13.shortcut.conv.norm": "decoder.layers.13.shortcut.norm", "decoder.model.15.conv.norm": "decoder.layers.15.norm", } __UpperCamelCase : Any = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } __UpperCamelCase : List[str] = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } __UpperCamelCase : Optional[Any] = [] __UpperCamelCase : List[str] = [] def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: for attribute in key.split(""".""" ): a = getattr(__lowerCamelCase , __lowerCamelCase ) if weight_type is not None: a = getattr(__lowerCamelCase , __lowerCamelCase ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value elif weight_type == "running_mean": a = value elif weight_type == "running_var": a = value elif weight_type == "num_batches_tracked": a = value elif weight_type == "weight_ih_l0": a = value elif weight_type == "weight_hh_l0": a = value elif weight_type == "bias_ih_l0": a = value elif weight_type == "bias_hh_l0": a = value elif weight_type == "weight_ih_l1": a = value elif weight_type == "weight_hh_l1": a = value elif weight_type == "bias_ih_l1": a = value elif weight_type == "bias_hh_l1": a = value else: a = value logger.info(f'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> int: for key in ignore_keys: if key.endswith(""".*""" ): if name.startswith(key[:-1] ): return True elif ".*." in key: a , a = key.split(""".*.""" ) if prefix in name and suffix in name: return True elif key in name: return True return False def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: a = [] if model_name == "encodec_24khz" or "encodec_32khz": a = MAPPING_24K elif model_name == "encodec_48khz": a = MAPPING_48K else: raise ValueError(f'Unsupported model: {model_name}' ) for name, value in orig_dict.items(): if should_ignore(__lowerCamelCase , __lowerCamelCase ): logger.info(f'{name} was ignored' ) continue a = False for key, mapped_key in MAPPING.items(): if "*" in key: a , a = key.split(""".*.""" ) if prefix in name and suffix in name: a = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith("""embed""" ) and name.endswith("""embed_avg""" ): continue a = True if "*" in mapped_key: a = name.split(__lowerCamelCase )[0].split(""".""" )[-2] a = mapped_key.replace("""*""" , __lowerCamelCase ) if "weight_g" in name: a = """weight_g""" elif "weight_v" in name: a = """weight_v""" elif "weight_ih_l0" in name: a = """weight_ih_l0""" elif "weight_hh_l0" in name: a = """weight_hh_l0""" elif "bias_ih_l0" in name: a = """bias_ih_l0""" elif "bias_hh_l0" in name: a = """bias_hh_l0""" elif "weight_ih_l1" in name: a = """weight_ih_l1""" elif "weight_hh_l1" in name: a = """weight_hh_l1""" elif "bias_ih_l1" in name: a = """bias_ih_l1""" elif "bias_hh_l1" in name: a = """bias_hh_l1""" elif "bias" in name: a = """bias""" elif "weight" in name: a = """weight""" elif "running_mean" in name: a = """running_mean""" elif "running_var" in name: a = """running_var""" elif "num_batches_tracked" in name: a = """num_batches_tracked""" else: a = None set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(f'Unused weights: {unused_weights}' ) @torch.no_grad() def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> str: if config_path is not None: a = EncodecConfig.from_pretrained(__lowerCamelCase ) else: a = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": a = [8, 5, 4, 4] a = [2.2] a = 64 a = 3_2000 a = 2048 a = False a = False a = False elif model_name == "encodec_48khz": a = [8, 5, 4, 2] a = [3.0, 6.0, 12.0, 24.0] a = 4_8000 a = 2 a = False a = """time_group_norm""" a = True a = 1.0 a = 0.01 else: raise ValueError(f'Unknown model name: {model_name}' ) a = EncodecModel(__lowerCamelCase ) a = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(__lowerCamelCase ) a = torch.load(__lowerCamelCase ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights a = original_checkpoint["""best_state"""] recursively_load_weights(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) model.save_pretrained(__lowerCamelCase ) if repo_id: print("""Pushing to the hub...""" ) feature_extractor.push_to_hub(__lowerCamelCase ) model.push_to_hub(__lowerCamelCase ) if __name__ == "__main__": __UpperCamelCase : Dict = argparse.ArgumentParser() parser.add_argument( "--model", default="encodec_24khz", type=str, help="The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.", ) parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
347
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = CanineTokenizer UpperCamelCase__ = False def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().setUp() a = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return CanineTokenizer.from_pretrained("""google/canine-s""" ) def lowerCamelCase__ ( self :Tuple , **__magic_name__ :Dict ): '''simple docstring''' a = self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) a = 1024 return tokenizer @require_torch def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.canine_tokenizer a = ["""Life is like a box of chocolates.""", """You never know what you're gonna get."""] # fmt: off a = [5_7344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 5_7345, 0, 0, 0, 0] # fmt: on a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) self.assertIsInstance(__magic_name__ , __magic_name__ ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = ["""Once there was a man.""", """He wrote a test in HuggingFace Tranformers."""] a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("""input_ids""" , __magic_name__ ) self.assertIn("""attention_mask""" , __magic_name__ ) self.assertIn("""token_type_ids""" , __magic_name__ ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = [ """What's the weater?""", """It's about 25 degrees.""", ] a = tokenizer( text_target=__magic_name__ , max_length=32 , padding="""max_length""" , truncation=__magic_name__ , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) shutil.rmtree(__magic_name__ ) a = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: a = chr(0Xe_0_0_7 ) additional_special_tokens.append(__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertIn(__magic_name__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) a = tokenizer.__class__.from_pretrained(__magic_name__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a , a = self.get_clean_sequence(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_5 a = chr(__magic_name__ ) tokenizer.add_special_tokens({"""cls_token""": special_token} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) a = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , input_encoded + special_token_id ) a = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertTrue(special_token not in decoded ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = chr(0Xe_0_0_5 ) a = chr(0Xe_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=__magic_name__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"""additional_special_tokens""": [SPECIAL_TOKEN_2]} ) a = tokenizer.tokenize(__magic_name__ ) a = tokenizer.tokenize(__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(token_a[0] , __magic_name__ ) self.assertEqual(token_a[0] , __magic_name__ ) @require_tokenizers def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(__magic_name__ ) tokenizer.from_pretrained(__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__magic_name__ ) with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = [new_token_a] a = [new_token_a] with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files a = tokenizer_class.from_pretrained(__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) a = 0Xe_0_0_7 a = chr(__magic_name__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained a = [AddedToken(__magic_name__ , lstrip=__magic_name__ )] a = tokenizer_class.from_pretrained( __magic_name__ , additional_special_tokens=__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = """hello world""" if self.space_between_special_tokens: a = """[CLS] hello world [SEP]""" else: a = input a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.decode(__magic_name__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(__magic_name__ , [output, output.lower()] ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = [ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] a = """a""" a = ord(__magic_name__ ) for attr in attributes_list: setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [] ) a = 0Xe_0_0_6 a = chr(__magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [additional_special_token_id] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [additional_special_token] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [additional_special_token_id] ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :str ): '''simple docstring''' pass def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass
347
1
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : Tuple = logging.get_logger(__name__) def __A ( __lowerCamelCase ) -> str: a = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: a = 128 elif "12-12" in model_name: a = 12 a = 12 elif "14-14" in model_name: a = 14 a = 14 elif "16-16" in model_name: a = 16 a = 16 else: raise ValueError("""Model not supported""" ) a = """huggingface/label-files""" if "speech-commands" in model_name: a = 35 a = """speech-commands-v2-id2label.json""" else: a = 527 a = """audioset-id2label.json""" a = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) a = {int(__lowerCamelCase ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} return config def __A ( __lowerCamelCase ) -> int: if "module.v" in name: a = name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: a = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: a = name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: a = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: a = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: a = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: a = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: a = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: a = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: a = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: a = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: a = name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: a = name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: a = name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: a = name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def __A ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: for key in orig_state_dict.copy().keys(): a = orig_state_dict.pop(__lowerCamelCase ) if "qkv" in key: a = key.split(""".""" ) a = int(key_split[3] ) a = config.hidden_size if "weight" in key: a = val[:dim, :] a = val[dim : dim * 2, :] a = val[-dim:, :] else: a = val[:dim] a = val[dim : dim * 2] a = val[-dim:] else: a = val return orig_state_dict def __A ( __lowerCamelCase ) -> str: a = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(__lowerCamelCase , __lowerCamelCase ) @torch.no_grad() def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=False ) -> Union[str, Any]: a = get_audio_spectrogram_transformer_config(__lowerCamelCase ) a = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict a = model_name_to_url[model_name] a = torch.hub.load_state_dict_from_url(__lowerCamelCase , map_location="""cpu""" ) # remove some keys remove_keys(__lowerCamelCase ) # rename some keys a = convert_state_dict(__lowerCamelCase , __lowerCamelCase ) # load 🤗 model a = ASTForAudioClassification(__lowerCamelCase ) model.eval() model.load_state_dict(__lowerCamelCase ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 a = -4.2677393 if """speech-commands""" not in model_name else -6.845978 a = 4.5689974 if """speech-commands""" not in model_name else 5.5654526 a = 1024 if """speech-commands""" not in model_name else 128 a = ASTFeatureExtractor(mean=__lowerCamelCase , std=__lowerCamelCase , max_length=__lowerCamelCase ) if "speech-commands" in model_name: a = load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) a = dataset[0]["""audio"""]["""array"""] else: a = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) a , a = torchaudio.load(__lowerCamelCase ) a = waveform.squeeze().numpy() a = feature_extractor(__lowerCamelCase , sampling_rate=1_6000 , return_tensors="""pt""" ) # forward pass a = model(**__lowerCamelCase ) a = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": a = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": a = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": a = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": a = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": a = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": a = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": a = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": a = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , __lowerCamelCase , atol=1E-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase ) print(f'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__lowerCamelCase ) print(f'Saving feature extractor to {pytorch_dump_folder_path}' ) feature_extractor.save_pretrained(__lowerCamelCase ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f'MIT/{model_name}' ) feature_extractor.push_to_hub(f'MIT/{model_name}' ) if __name__ == "__main__": __UpperCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="ast-finetuned-audioset-10-10-0.4593", type=str, help="Name of the Audio Spectrogram Transformer model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) __UpperCamelCase : Any = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
347
def __A ( __lowerCamelCase ) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
347
1
from __future__ import annotations from typing import Generic, TypeVar __UpperCamelCase : Union[str, Any] = TypeVar("T") class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple , __magic_name__ :T ): '''simple docstring''' a = data a = self a = 0 class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T ): '''simple docstring''' a = DisjointSetTreeNode(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :T ): '''simple docstring''' a = self.map[data] if elem_ref != elem_ref.parent: a = self.find_set(elem_ref.parent.data ) return elem_ref.parent def lowerCamelCase__ ( self :List[Any] , __magic_name__ :DisjointSetTreeNode[T] , __magic_name__ :DisjointSetTreeNode[T] ): '''simple docstring''' if nodea.rank > nodea.rank: a = nodea else: a = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T , __magic_name__ :T ): '''simple docstring''' self.link(self.find_set(__magic_name__ ) , self.find_set(__magic_name__ ) ) class __lowerCAmelCase ( Generic[T] ): def __init__( self :Union[str, Any] ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :T ): '''simple docstring''' if node not in self.connections: a = {} def lowerCamelCase__ ( self :Any , __magic_name__ :T , __magic_name__ :T , __magic_name__ :int ): '''simple docstring''' self.add_node(__magic_name__ ) self.add_node(__magic_name__ ) a = weight a = weight def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] a = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda __magic_name__ : x[2] ) # creating the disjoint set a = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__magic_name__ ) # MST generation a = 0 a = 0 a = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: a , a , a = edges[index] index += 1 a = disjoint_set.find_set(__magic_name__ ) a = disjoint_set.find_set(__magic_name__ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__magic_name__ , __magic_name__ , __magic_name__ ) disjoint_set.union(__magic_name__ , __magic_name__ ) return graph
347
def __A ( __lowerCamelCase ) -> int: if not numbers: return 0 if not isinstance(__lowerCamelCase , (list, tuple) ) or not all( isinstance(__lowerCamelCase , __lowerCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) a = a = a = numbers[0] for i in range(1 , len(__lowerCamelCase ) ): # update the maximum and minimum subarray products a = numbers[i] if number < 0: a , a = min_till_now, max_till_now a = max(__lowerCamelCase , max_till_now * number ) a = min(__lowerCamelCase , min_till_now * number ) # update the maximum product found till now a = max(__lowerCamelCase , __lowerCamelCase ) return max_prod
347
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""" ) def __A ( ) -> Optional[Any]: a = 10 a = datasets.Features( { """tokens""": datasets.Sequence(datasets.Value("""string""" ) ), """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""] ) ), """answers""": datasets.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), """id""": datasets.Value("""int64""" ), } ) a = datasets.Dataset.from_dict( { """tokens""": [["""foo"""] * 5] * n, """labels""": [[1] * 5] * n, """answers""": [{"""answer_start""": [97], """text""": ["""1976"""]}] * 10, """id""": list(range(__lowerCamelCase ) ), } , features=__lowerCamelCase , ) return dataset @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> int: a = str(tmp_path_factory.mktemp("""data""" ) / """file.arrow""" ) dataset.map(cache_file_name=__lowerCamelCase ) return filename # FILE_CONTENT + files __UpperCamelCase : Union[str, Any] = "\\n Text data.\n Second line of data." @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> List[str]: a = tmp_path_factory.mktemp("""data""" ) / """file.txt""" a = FILE_CONTENT with open(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase ) return filename @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Tuple: import bza a = tmp_path_factory.mktemp("""data""" ) / """file.txt.bz2""" a = bytes(__lowerCamelCase , """utf-8""" ) with bza.open(__lowerCamelCase , """wb""" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> List[Any]: import gzip a = str(tmp_path_factory.mktemp("""data""" ) / """file.txt.gz""" ) a = bytes(__lowerCamelCase , """utf-8""" ) with gzip.open(__lowerCamelCase , """wb""" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Dict: if datasets.config.LZ4_AVAILABLE: import lza.frame a = tmp_path_factory.mktemp("""data""" ) / """file.txt.lz4""" a = bytes(__lowerCamelCase , """utf-8""" ) with lza.frame.open(__lowerCamelCase , """wb""" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> List[str]: if datasets.config.PY7ZR_AVAILABLE: import pyazr a = tmp_path_factory.mktemp("""data""" ) / """file.txt.7z""" with pyazr.SevenZipFile(__lowerCamelCase , """w""" ) as archive: archive.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> List[str]: import tarfile a = tmp_path_factory.mktemp("""data""" ) / """file.txt.tar""" with tarfile.TarFile(__lowerCamelCase , """w""" ) as f: f.add(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> List[str]: import lzma a = tmp_path_factory.mktemp("""data""" ) / """file.txt.xz""" a = bytes(__lowerCamelCase , """utf-8""" ) with lzma.open(__lowerCamelCase , """wb""" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> Dict: import zipfile a = tmp_path_factory.mktemp("""data""" ) / """file.txt.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> str: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd a = tmp_path_factory.mktemp("""data""" ) / """file.txt.zst""" a = bytes(__lowerCamelCase , """utf-8""" ) with zstd.open(__lowerCamelCase , """wb""" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Any: a = tmp_path_factory.mktemp("""data""" ) / """file.xml""" a = textwrap.dedent( """\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <tmx version=\"1.4\"> <header segtype=\"sentence\" srclang=\"ca\" /> <body> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv> </tu> </body> </tmx>""" ) with open(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase ) return filename __UpperCamelCase : Dict = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] __UpperCamelCase : Tuple = [ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] __UpperCamelCase : List[Any] = { "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } __UpperCamelCase : Optional[Any] = [ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] __UpperCamelCase : Union[str, Any] = [ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope="""session""" ) def __A ( ) -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Union[str, Any]: a = datasets.Dataset.from_dict(__lowerCamelCase ) a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.arrow""" ) dataset.map(cache_file_name=__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> int: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.sqlite""" ) with contextlib.closing(sqlitea.connect(__lowerCamelCase ) ) as con: a = con.cursor() cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)""" ) for item in DATA: cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)""" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Tuple: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.csv""" ) with open(__lowerCamelCase , """w""" , newline="""""" ) as f: a = csv.DictWriter(__lowerCamelCase , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> int: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.csv""" ) with open(__lowerCamelCase , """w""" , newline="""""" ) as f: a = csv.DictWriter(__lowerCamelCase , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> Dict: import bza a = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.bz2""" with open(__lowerCamelCase , """rb""" ) as f: a = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(__lowerCamelCase , """wb""" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: a = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: a = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.basename(csv_path.replace(""".csv""" , """.CSV""" ) ) ) f.write(__lowerCamelCase , arcname=os.path.basename(csva_path.replace(""".csv""" , """.CSV""" ) ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Tuple: a = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.csv.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.join("""main_dir""" , os.path.basename(__lowerCamelCase ) ) ) f.write(__lowerCamelCase , arcname=os.path.join("""main_dir""" , os.path.basename(__lowerCamelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Tuple: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.parquet""" ) a = pa.schema( { """col_1""": pa.string(), """col_2""": pa.intaa(), """col_3""": pa.floataa(), } ) with open(__lowerCamelCase , """wb""" ) as f: a = pq.ParquetWriter(__lowerCamelCase , schema=__lowerCamelCase ) a = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(__lowerCamelCase ) )] for k in DATA[0]} , schema=__lowerCamelCase ) writer.write_table(__lowerCamelCase ) writer.close() return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> List[str]: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) a = {"""data""": DATA} with open(__lowerCamelCase , """w""" ) as f: json.dump(__lowerCamelCase , __lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Tuple: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) a = {"""data""": DATA_DICT_OF_LISTS} with open(__lowerCamelCase , """w""" ) as f: json.dump(__lowerCamelCase , __lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Any: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl""" ) with open(__lowerCamelCase , """w""" ) as f: for item in DATA: f.write(json.dumps(__lowerCamelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> List[str]: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.jsonl""" ) with open(__lowerCamelCase , """w""" ) as f: for item in DATA: f.write(json.dumps(__lowerCamelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Tuple: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset_312.jsonl""" ) with open(__lowerCamelCase , """w""" ) as f: for item in DATA_312: f.write(json.dumps(__lowerCamelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Any: a = str(tmp_path_factory.mktemp("""data""" ) / """dataset-str.jsonl""" ) with open(__lowerCamelCase , """w""" ) as f: for item in DATA_STR: f.write(json.dumps(__lowerCamelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> Tuple: import gzip a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt.gz""" ) with open(__lowerCamelCase , """rb""" ) as orig_file: with gzip.open(__lowerCamelCase , """wb""" ) as zipped_file: zipped_file.writelines(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> List[Any]: import gzip a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.gz""" ) with open(__lowerCamelCase , """rb""" ) as orig_file: with gzip.open(__lowerCamelCase , """wb""" ) as zipped_file: zipped_file.writelines(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: a = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: a = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.join("""nested""" , os.path.basename(__lowerCamelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: a = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.jsonl.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.join("""main_dir""" , os.path.basename(__lowerCamelCase ) ) ) f.write(__lowerCamelCase , arcname=os.path.join("""main_dir""" , os.path.basename(__lowerCamelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Tuple: a = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.tar""" with tarfile.TarFile(__lowerCamelCase , """w""" ) as f: f.add(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) f.add(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: a = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.tar""" with tarfile.TarFile(__lowerCamelCase , """w""" ) as f: f.add(__lowerCamelCase , arcname=os.path.join("""nested""" , os.path.basename(__lowerCamelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Union[str, Any]: a = ["""0""", """1""", """2""", """3"""] a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt""" ) with open(__lowerCamelCase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> Dict: a = ["""0""", """1""", """2""", """3"""] a = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.txt""" ) with open(__lowerCamelCase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> int: a = ["""0""", """1""", """2""", """3"""] a = tmp_path_factory.mktemp("""data""" ) / """dataset.abc""" with open(__lowerCamelCase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict: a = tmp_path_factory.mktemp("""data""" ) / """dataset.text.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: a = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.text.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.join("""main_dir""" , os.path.basename(__lowerCamelCase ) ) ) f.write(__lowerCamelCase , arcname=os.path.join("""main_dir""" , os.path.basename(__lowerCamelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: a = tmp_path_factory.mktemp("""data""" ) / """dataset.ext.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.basename("""unsupported.ext""" ) ) f.write(__lowerCamelCase , arcname=os.path.basename("""unsupported_2.ext""" ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> List[Any]: a = """\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""] ) a = str(tmp_path_factory.mktemp("""data""" ) / """dataset_with_unicode_new_lines.txt""" ) with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture(scope="""session""" ) def __A ( ) -> Any: return os.path.join("""tests""" , """features""" , """data""" , """test_image_rgb.jpg""" ) @pytest.fixture(scope="""session""" ) def __A ( ) -> Tuple: return os.path.join("""tests""" , """features""" , """data""" , """test_audio_44100.wav""" ) @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: a = tmp_path_factory.mktemp("""data""" ) / """dataset.img.zip""" with zipfile.ZipFile(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ) ) f.write(__lowerCamelCase , arcname=os.path.basename(__lowerCamelCase ).replace(""".jpg""" , """2.jpg""" ) ) return path @pytest.fixture(scope="""session""" ) def __A ( __lowerCamelCase ) -> List[str]: a = tmp_path_factory.mktemp("""data_dir""" ) (data_dir / "subdir").mkdir() with open(data_dir / """subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden file with open(data_dir / """subdir""" / """.test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / """.subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """.subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) return data_dir
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCamelCase : Optional[Any] = { "configuration_wav2vec2": ["WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2Config"], "feature_extraction_wav2vec2": ["Wav2Vec2FeatureExtractor"], "processing_wav2vec2": ["Wav2Vec2Processor"], "tokenization_wav2vec2": ["Wav2Vec2CTCTokenizer", "Wav2Vec2Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = [ "WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ForAudioFrameClassification", "Wav2Vec2ForCTC", "Wav2Vec2ForMaskedLM", "Wav2Vec2ForPreTraining", "Wav2Vec2ForSequenceClassification", "Wav2Vec2ForXVector", "Wav2Vec2Model", "Wav2Vec2PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ "TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWav2Vec2ForCTC", "TFWav2Vec2Model", "TFWav2Vec2PreTrainedModel", "TFWav2Vec2ForSequenceClassification", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "FlaxWav2Vec2ForCTC", "FlaxWav2Vec2ForPreTraining", "FlaxWav2Vec2Model", "FlaxWav2Vec2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''ClapFeatureExtractor''' UpperCamelCase__ = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self :Dict , __magic_name__ :Any , __magic_name__ :Optional[int] ): '''simple docstring''' super().__init__(__magic_name__ , __magic_name__ ) def __call__( self :Tuple , __magic_name__ :Union[str, Any]=None , __magic_name__ :List[Any]=None , __magic_name__ :str=None , **__magic_name__ :str ): '''simple docstring''' a = kwargs.pop("""sampling_rate""" , __magic_name__ ) if text is None and audios is None: raise ValueError("""You have to specify either text or audios. Both cannot be none.""" ) if text is not None: a = self.tokenizer(__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) if audios is not None: a = self.feature_extractor( __magic_name__ , sampling_rate=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) if text is not None and audios is not None: a = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__magic_name__ ) , tensor_type=__magic_name__ ) def lowerCamelCase__ ( self :List[str] , *__magic_name__ :Optional[Any] , **__magic_name__ :Union[str, Any] ): '''simple docstring''' return self.tokenizer.batch_decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :List[str] , *__magic_name__ :Dict , **__magic_name__ :Optional[Any] ): '''simple docstring''' return self.tokenizer.decode(*__magic_name__ , **__magic_name__ ) @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.tokenizer.model_input_names a = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
347
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCamelCase ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(__lowerCamelCase ) assert result == expected
347
1
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer a = flax_key_tuple[:-1] + ("""weight""",) a = torch.permute(__lowerCamelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCamelCase ): # linear layer a = flax_key_tuple[:-1] + ("""weight""",) a = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: a = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: if "metadata" in layer: a = layer.split("""metadata""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: a = layer.split("""kvstore""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: a = layer.split("""/""" ) a = """/""".join(split_layer[:-1] ) a = (split_layer[-1],) if "kvstore/path" in layer: a = f'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: a = """file""" else: a = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __A ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: a = rename_keys(__lowerCamelCase ) a = {} for k, v in current_block.items(): a = v a = new_current_block torch.save(__lowerCamelCase , __lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = WEIGHTS_NAME ) -> List[str]: a = convert_file_size_to_int(__lowerCamelCase ) a = [] a = {} a = 0 a = 0 os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: a = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] a = flatten_dict(__lowerCamelCase , sep="""/""" ) a = {} for layer in checkpoint_info.keys(): a , a , a = get_key_and_tensorstore_dict( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if curr_real_layer_name in all_layers: a = content else: a = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() a = torch.tensor(__lowerCamelCase ) a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts a , a = rename_base_flax_keys(tuple(key.split("""/""" ) ) , __lowerCamelCase ) a = """/""".join(__lowerCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: a = os.path.join( __lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block a = {} a = 0 a = raw_weights.to(getattr(__lowerCamelCase , __lowerCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index a = {} a = {} for idx, shard in enumerate(__lowerCamelCase ): a = weights_name.replace( """.bin""" , f'-{idx+1:05d}-of-{len(__lowerCamelCase ):05d}.bin' ) # len(sharded_state_dicts):05d} a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{idx+1:05d}-of-???.bin' ) ) os.rename(__lowerCamelCase , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) a = shard for key in shard: a = shard_file # Add the metadata a = {"""total_size""": total_size} a = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(__lowerCamelCase , __lowerCamelCase ) , """w""" , encoding="""utf-8""" ) as f: a = json.dumps(__lowerCamelCase , indent=2 , sort_keys=__lowerCamelCase ) + """\n""" f.write(__lowerCamelCase ) return metadata, index if __name__ == "__main__": __UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __UpperCamelCase : Any = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __A ( ) -> Tuple: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer a = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) a = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) a = TaTokenizer.from_pretrained("""t5-small""" ) a = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" a = tokenizer(__lowerCamelCase , return_tensors="""pt""" ).input_ids a = model.generate(__lowerCamelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
347
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __A ( __lowerCamelCase ) -> bool: a = int(number**0.5 ) return number == sq * sq def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> tuple[int, int]: a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den a = x_den * y_den * z_den a = gcd(__lowerCamelCase , __lowerCamelCase ) top //= hcf bottom //= hcf return top, bottom def __A ( __lowerCamelCase = 35 ) -> int: a = set() a = 42 a = Fraction(0 ) a = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 a = x_num * y_den + x_den * y_num a = x_den * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) a = x_den * x_den * y_den * y_den if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=-1 a = x_num * y_num a = x_den * y_num + x_num * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = x_num * x_num * y_num * y_num a = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) for num, den in unique_s: total += Fraction(__lowerCamelCase , __lowerCamelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(F'{solution() = }')
347
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase : Any = logging.get_logger(__name__) __UpperCamelCase : Any = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''big_bird''' def __init__( self :Union[str, Any] , __magic_name__ :Any=5_0358 , __magic_name__ :List[str]=768 , __magic_name__ :List[str]=12 , __magic_name__ :Optional[int]=12 , __magic_name__ :List[str]=3072 , __magic_name__ :Dict="gelu_new" , __magic_name__ :List[Any]=0.1 , __magic_name__ :Any=0.1 , __magic_name__ :Optional[int]=4096 , __magic_name__ :Union[str, Any]=2 , __magic_name__ :int=0.02 , __magic_name__ :int=1E-1_2 , __magic_name__ :Any=True , __magic_name__ :Any=0 , __magic_name__ :Union[str, Any]=1 , __magic_name__ :Any=2 , __magic_name__ :Dict=66 , __magic_name__ :int="block_sparse" , __magic_name__ :List[Any]=True , __magic_name__ :Dict=False , __magic_name__ :Tuple=64 , __magic_name__ :Dict=3 , __magic_name__ :Union[str, Any]=None , **__magic_name__ :Optional[Any] , ): '''simple docstring''' super().__init__( pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , sep_token_id=__magic_name__ , **__magic_name__ , ) a = vocab_size a = max_position_embeddings a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = initializer_range a = type_vocab_size a = layer_norm_eps a = use_cache a = rescale_embeddings a = attention_type a = use_bias a = block_size a = num_random_blocks a = classifier_dropout class __lowerCAmelCase ( __magic_name__ ): @property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' if self.task == "multiple-choice": a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
347
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :List[str] , __magic_name__ :List[str] , __magic_name__ :List[Any]=13 , __magic_name__ :Any=7 , __magic_name__ :Optional[int]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :Any=99 , __magic_name__ :List[str]=32 , __magic_name__ :List[str]=5 , __magic_name__ :str=4 , __magic_name__ :str=37 , __magic_name__ :Optional[int]="gelu" , __magic_name__ :int=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Tuple=16 , __magic_name__ :Tuple=2 , __magic_name__ :List[str]=0.02 , __magic_name__ :Any=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = FlaxRoFormerModelTester(self ) @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) a = jnp.array([[0, 1, 2, 3, 4, 5]] ) a = model(__magic_name__ )[0] a = 5_0000 a = (1, 6, vocab_size) self.assertEqual(output.shape , __magic_name__ ) a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCamelCase ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(__lowerCamelCase ) assert result == expected
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch __UpperCamelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = ['''pixel_values'''] def __init__( self :str , __magic_name__ :bool = True , __magic_name__ :Optional[Dict[str, int]] = None , __magic_name__ :PILImageResampling = PILImageResampling.BILINEAR , __magic_name__ :bool = True , __magic_name__ :Dict[str, int] = None , __magic_name__ :bool = True , __magic_name__ :Union[int, float] = 1 / 255 , __magic_name__ :bool = True , __magic_name__ :Optional[Union[float, List[float]]] = None , __magic_name__ :Optional[Union[float, List[float]]] = None , **__magic_name__ :Optional[int] , ): '''simple docstring''' super().__init__(**__magic_name__ ) a = size if size is not None else {"""shortest_edge""": 256} a = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) a = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} a = get_size_dict(__magic_name__ , param_name="""crop_size""" ) a = do_resize a = size a = resample a = do_center_crop a = crop_size a = do_rescale a = rescale_factor a = do_normalize a = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCamelCase__ ( self :int , __magic_name__ :np.ndarray , __magic_name__ :Dict[str, int] , __magic_name__ :PILImageResampling = PILImageResampling.BICUBIC , __magic_name__ :Optional[Union[str, ChannelDimension]] = None , **__magic_name__ :Optional[Any] , ): '''simple docstring''' a = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) a = get_resize_output_image_size(__magic_name__ , size=size["""shortest_edge"""] , default_to_square=__magic_name__ ) return resize(__magic_name__ , size=__magic_name__ , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :np.ndarray , __magic_name__ :Dict[str, int] , __magic_name__ :Optional[Union[str, ChannelDimension]] = None , **__magic_name__ :Dict , ): '''simple docstring''' a = get_size_dict(__magic_name__ ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(__magic_name__ , size=(size["""height"""], size["""width"""]) , data_format=__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :np.ndarray , __magic_name__ :float , __magic_name__ :Optional[Union[str, ChannelDimension]] = None , **__magic_name__ :str ): '''simple docstring''' return rescale(__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :np.ndarray , __magic_name__ :Union[float, List[float]] , __magic_name__ :Union[float, List[float]] , __magic_name__ :Optional[Union[str, ChannelDimension]] = None , **__magic_name__ :Optional[Any] , ): '''simple docstring''' return normalize(__magic_name__ , mean=__magic_name__ , std=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :ImageInput , __magic_name__ :Optional[bool] = None , __magic_name__ :Dict[str, int] = None , __magic_name__ :PILImageResampling = None , __magic_name__ :bool = None , __magic_name__ :Dict[str, int] = None , __magic_name__ :Optional[bool] = None , __magic_name__ :Optional[float] = None , __magic_name__ :Optional[bool] = None , __magic_name__ :Optional[Union[float, List[float]]] = None , __magic_name__ :Optional[Union[float, List[float]]] = None , __magic_name__ :Optional[Union[str, TensorType]] = None , __magic_name__ :Union[str, ChannelDimension] = ChannelDimension.FIRST , **__magic_name__ :Union[str, Any] , ): '''simple docstring''' a = do_resize if do_resize is not None else self.do_resize a = size if size is not None else self.size a = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) a = resample if resample is not None else self.resample a = do_center_crop if do_center_crop is not None else self.do_center_crop a = crop_size if crop_size is not None else self.crop_size a = get_size_dict(__magic_name__ , param_name="""crop_size""" ) a = do_rescale if do_rescale is not None else self.do_rescale a = rescale_factor if rescale_factor is not None else self.rescale_factor a = do_normalize if do_normalize is not None else self.do_normalize a = image_mean if image_mean is not None else self.image_mean a = image_std if image_std is not None else self.image_std a = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. a = [to_numpy_array(__magic_name__ ) for image in images] if do_resize: a = [self.resize(image=__magic_name__ , size=__magic_name__ , resample=__magic_name__ ) for image in images] if do_center_crop: a = [self.center_crop(image=__magic_name__ , size=__magic_name__ ) for image in images] if do_rescale: a = [self.rescale(image=__magic_name__ , scale=__magic_name__ ) for image in images] if do_normalize: a = [self.normalize(image=__magic_name__ , mean=__magic_name__ , std=__magic_name__ ) for image in images] a = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] a = {"""pixel_values""": images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :Dict , __magic_name__ :List[Tuple] = None ): '''simple docstring''' a = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__magic_name__ ) != len(__magic_name__ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(__magic_name__ ): a = target_sizes.numpy() a = [] for idx in range(len(__magic_name__ ) ): a = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=__magic_name__ ) a = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__magic_name__ ) else: a = logits.argmax(dim=1 ) a = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
347
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = (IPNDMScheduler,) UpperCamelCase__ = (('''num_inference_steps''', 50),) def lowerCamelCase__ ( self :Any , **__magic_name__ :Optional[Any] ): '''simple docstring''' a = {"""num_train_timesteps""": 1000} config.update(**__magic_name__ ) return config def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple=0 , **__magic_name__ :Optional[int] ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] , __magic_name__ :List[Any]=0 , **__magic_name__ :Any ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals (must be after setting timesteps) a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) # copy over dummy past residuals new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residual (must be after setting timesteps) a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Optional[Any] , **__magic_name__ :Optional[int] ): '''simple docstring''' a = self.scheduler_classes[0] a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) a = 10 a = self.dummy_model() a = self.dummy_sample_deter scheduler.set_timesteps(__magic_name__ ) for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample return sample def lowerCamelCase__ ( self :str ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) a = self.dummy_sample a = 0.1 * sample if num_inference_steps is not None and hasattr(__magic_name__ , """set_timesteps""" ): scheduler.set_timesteps(__magic_name__ ) elif num_inference_steps is not None and not hasattr(__magic_name__ , """set_timesteps""" ): a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] a = dummy_past_residuals[:] a = scheduler.timesteps[5] a = scheduler.timesteps[6] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.full_loop() a = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_mean.item() - 254_0529 ) < 10
347
1
import argparse from collections import defaultdict import yaml __UpperCamelCase : str = "docs/source/en/_toctree.yml" def __A ( __lowerCamelCase ) -> Dict: a = defaultdict(__lowerCamelCase ) for doc in model_doc: counts[doc["local"]] += 1 a = [key for key, value in counts.items() if value > 1] a = [] for duplicate_key in duplicates: a = list({doc["""title"""] for doc in model_doc if doc["""local"""] == duplicate_key} ) if len(__lowerCamelCase ) > 1: raise ValueError( f'{duplicate_key} is present several times in the documentation table of content at ' """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc["""local"""]] == 1] ) # Sort return sorted(__lowerCamelCase , key=lambda __lowerCamelCase : s["title"].lower() ) def __A ( __lowerCamelCase=False ) -> Tuple: with open(__lowerCamelCase , encoding="""utf-8""" ) as f: a = yaml.safe_load(f.read() ) # Get to the API doc a = 0 while content[api_idx]["title"] != "API": api_idx += 1 a = content[api_idx]["""sections"""] # Then to the model doc a = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 a = api_doc[model_idx]["""sections"""] a = [(idx, section) for idx, section in enumerate(__lowerCamelCase ) if """sections""" in section] a = False for idx, modality_doc in modalities_docs: a = modality_doc["""sections"""] a = clean_model_doc_toc(__lowerCamelCase ) if old_modality_doc != new_modality_doc: a = True if overwrite: a = new_modality_doc if diff: if overwrite: a = model_doc a = api_doc with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(__lowerCamelCase , allow_unicode=__lowerCamelCase ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": __UpperCamelCase : int = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") __UpperCamelCase : List[str] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
347
__UpperCamelCase : Dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __A ( ) -> None: a = input("""Enter message: """ ) a = input("""Enter key [alphanumeric]: """ ) a = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): a = """encrypt""" a = encrypt_message(__lowerCamelCase , __lowerCamelCase ) elif mode.lower().startswith("""d""" ): a = """decrypt""" a = decrypt_message(__lowerCamelCase , __lowerCamelCase ) print(f'\n{mode.title()}ed message:' ) print(__lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """encrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """decrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: a = [] a = 0 a = key.upper() for symbol in message: a = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__lowerCamelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__lowerCamelCase ): a = 0 else: translated.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) if __name__ == "__main__": main()
347
1
import random class __lowerCAmelCase : @staticmethod def lowerCamelCase__ ( __magic_name__ :str ): '''simple docstring''' a = [ord(__magic_name__ ) for i in text] a = [] a = [] for i in plain: a = random.randint(1 , 300 ) a = (i + k) * k cipher.append(__magic_name__ ) key.append(__magic_name__ ) return cipher, key @staticmethod def lowerCamelCase__ ( __magic_name__ :list[int] , __magic_name__ :list[int] ): '''simple docstring''' a = [] for i in range(len(__magic_name__ ) ): a = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(__magic_name__ ) ) return "".join(__magic_name__ ) if __name__ == "__main__": __UpperCamelCase , __UpperCamelCase : int = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
347
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Tuple=13 , __magic_name__ :List[Any]=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :List[str]=True , __magic_name__ :str=99 , __magic_name__ :Optional[Any]=32 , __magic_name__ :Union[str, Any]=5 , __magic_name__ :Any=4 , __magic_name__ :int=37 , __magic_name__ :Tuple="gelu" , __magic_name__ :List[str]=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :Tuple=512 , __magic_name__ :Dict=16 , __magic_name__ :Optional[int]=2 , __magic_name__ :Optional[int]=0.02 , __magic_name__ :Optional[Any]=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :int ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = True a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = FlaxRobertaModelTester(self ) @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""roberta-base""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ )
347
1
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class __lowerCAmelCase : def __init__( self :List[Any] , __magic_name__ :Union[str, Any] , __magic_name__ :Any=2 , __magic_name__ :Dict=True , __magic_name__ :Dict=False , __magic_name__ :Dict=10 , __magic_name__ :Optional[Any]=3 , __magic_name__ :Tuple=32 * 8 , __magic_name__ :List[Any]=32 * 8 , __magic_name__ :Dict=4 , __magic_name__ :List[str]=64 , ): '''simple docstring''' a = parent a = batch_size a = is_training a = use_auxiliary_loss a = num_queries a = num_channels a = min_size a = max_size a = num_labels a = hidden_dim a = hidden_dim def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __magic_name__ ) a = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__magic_name__ ) a = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__magic_name__ ) > 0.5 ).float() a = (torch.rand((self.batch_size, self.num_labels) , device=__magic_name__ ) > 0.5).long() a = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowerCamelCase__ ( self :str ): '''simple docstring''' a = MaskaFormerConfig( hidden_size=self.hidden_dim , ) a = self.num_queries a = self.num_labels a = [1, 1, 1, 1] a = self.num_channels a = 64 a = 128 a = self.hidden_dim a = self.hidden_dim a = self.hidden_dim return config def lowerCamelCase__ ( self :str ): '''simple docstring''' a , a , a , a , a = self.prepare_config_and_inputs() a = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def lowerCamelCase__ ( self :int , __magic_name__ :Union[str, Any] , __magic_name__ :Dict ): '''simple docstring''' a = output.encoder_hidden_states a = output.pixel_decoder_hidden_states a = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__magic_name__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__magic_name__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__magic_name__ ) , config.decoder_layers ) def lowerCamelCase__ ( self :Dict , __magic_name__ :str , __magic_name__ :str , __magic_name__ :Union[str, Any] , __magic_name__ :Tuple=False ): '''simple docstring''' with torch.no_grad(): a = MaskaFormerModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model(pixel_values=__magic_name__ , pixel_mask=__magic_name__ ) a = model(__magic_name__ , output_hidden_states=__magic_name__ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :int , __magic_name__ :List[str] , __magic_name__ :str , __magic_name__ :Optional[Any] , __magic_name__ :List[Any] , __magic_name__ :Tuple ): '''simple docstring''' a = MaskaFormerForUniversalSegmentation(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() def comm_check_on_output(__magic_name__ :Union[str, Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): a = model(pixel_values=__magic_name__ , pixel_mask=__magic_name__ ) a = model(__magic_name__ ) comm_check_on_output(__magic_name__ ) a = model( pixel_values=__magic_name__ , pixel_mask=__magic_name__ , mask_labels=__magic_name__ , class_labels=__magic_name__ ) comm_check_on_output(__magic_name__ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () UpperCamelCase__ = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = MaskaFormerModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self :Any ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__magic_name__ , **__magic_name__ , output_hidden_states=__magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__magic_name__ ) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""" ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former is not a generative model""" ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former does not use token embeddings""" ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def lowerCamelCase__ ( self :int ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __magic_name__ ) @slow def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: a = MaskaFormerModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = (self.model_tester.min_size,) * 2 a = { """pixel_values""": torch.randn((2, 3, *size) , device=__magic_name__ ), """mask_labels""": torch.randn((2, 10, *size) , device=__magic_name__ ), """class_labels""": torch.zeros(2 , 10 , device=__magic_name__ ).long(), } a = self.model_tester.get_config() a = MaskaFormerForUniversalSegmentation(__magic_name__ ).to(__magic_name__ ) a = model(**__magic_name__ ) self.assertTrue(outputs.loss is not None ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__magic_name__ , **__magic_name__ , output_hidden_states=__magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__magic_name__ ).to(__magic_name__ ) a = model(**__magic_name__ , output_attentions=__magic_name__ ) self.assertTrue(outputs.attentions is not None ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' if not self.model_tester.is_training: return a = self.all_model_classes[1] a , a , a , a , a = self.model_tester.prepare_config_and_inputs() a = model_class(__magic_name__ ) model.to(__magic_name__ ) model.train() a = model(__magic_name__ , mask_labels=__magic_name__ , class_labels=__magic_name__ ).loss loss.backward() def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.all_model_classes[1] a , a , a , a , a = self.model_tester.prepare_config_and_inputs() a = True a = True a = model_class(__magic_name__ ).to(__magic_name__ ) model.train() a = model(__magic_name__ , mask_labels=__magic_name__ , class_labels=__magic_name__ ) a = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() a = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() a = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() a = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__magic_name__ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __UpperCamelCase : List[str] = 1E-4 def __A ( ) -> Dict: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :str ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__magic_name__ ) a = self.default_image_processor a = prepare_img() a = image_processor(__magic_name__ , return_tensors="""pt""" ).to(__magic_name__ ) a = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__magic_name__ , (1, 3, 384, 384) ) with torch.no_grad(): a = model(**__magic_name__ ) a = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(__magic_name__ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __magic_name__ , atol=__magic_name__ ) ) a = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(__magic_name__ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __magic_name__ , atol=__magic_name__ ) ) a = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(__magic_name__ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __magic_name__ , atol=__magic_name__ ) ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__magic_name__ ).eval() a = self.default_image_processor a = prepare_img() a = image_processor(__magic_name__ , return_tensors="""pt""" ).to(__magic_name__ ) a = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__magic_name__ , (1, 3, 384, 384) ) with torch.no_grad(): a = model(**__magic_name__ ) # masks_queries_logits a = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) a = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] a = torch.tensor(__magic_name__ ).to(__magic_name__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __magic_name__ , atol=__magic_name__ ) ) # class_queries_logits a = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) a = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __magic_name__ , atol=__magic_name__ ) ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__magic_name__ ).eval() a = self.default_image_processor a = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="""pt""" , ) a = inputs["""pixel_values"""].to(__magic_name__ ) a = [el.to(__magic_name__ ) for el in inputs["""mask_labels"""]] a = [el.to(__magic_name__ ) for el in inputs["""class_labels"""]] with torch.no_grad(): a = model(**__magic_name__ ) self.assertTrue(outputs.loss is not None )
347
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __UpperCamelCase : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): UpperCamelCase__ = None UpperCamelCase__ = "utf-8" UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = True # deprecated UpperCamelCase__ = None # deprecated UpperCamelCase__ = 10 << 20 # 10MB UpperCamelCase__ = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): UpperCamelCase__ = JsonConfig def lowerCamelCase__ ( self :str ): '''simple docstring''' if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) a = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__magic_name__ , (str, list, tuple) ): a = data_files if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] a = [] for split_name, files in data_files.items(): if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] splits.append(datasets.SplitGenerator(name=__magic_name__ , gen_kwargs={"""files""": files} ) ) return splits def lowerCamelCase__ ( self :List[str] , __magic_name__ :pa.Table ): '''simple docstring''' if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): a = self.config.features.arrow_schema.field(__magic_name__ ).type a = pa_table.append_column(__magic_name__ , pa.array([None] * len(__magic_name__ ) , type=__magic_name__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example a = table_cast(__magic_name__ , self.config.features.arrow_schema ) return pa_table def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Union[str, Any] ): '''simple docstring''' for file_idx, file in enumerate(itertools.chain.from_iterable(__magic_name__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) # We keep only the field we are interested in a = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__magic_name__ , (list, tuple) ): a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} else: a = dataset a = pa.Table.from_pydict(__magic_name__ ) yield file_idx, self._cast_table(__magic_name__ ) # If the file has one json object per line else: with open(__magic_name__ , """rb""" ) as f: a = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small a = max(self.config.chunksize // 32 , 16 << 10 ) a = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: a = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__magic_name__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": a = batch.decode(self.config.encoding , errors=__magic_name__ ).encode("""utf-8""" ) try: while True: try: a = paj.read_json( io.BytesIO(__magic_name__ ) , read_options=paj.ReadOptions(block_size=__magic_name__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__magic_name__ , pa.ArrowInvalid ) and "straddling" not in str(__magic_name__ ) or block_size > len(__magic_name__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F'Batch of {len(__magic_name__ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( __magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) except json.JSONDecodeError: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__magic_name__ , __magic_name__ ): # list is the only sequence type supported in JSON try: a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} a = pa.Table.from_pydict(__magic_name__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError(F'Not able to read records in the JSON file at {file}.' ) from None yield file_idx, self._cast_table(__magic_name__ ) break else: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError( F'Not able to read records in the JSON file at {file}. ' F'You should probably indicate the field of the JSON file containing your records. ' F'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ' F'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__magic_name__ ) batch_idx += 1
347
1
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin __UpperCamelCase : Optional[int] = get_tests_dir("fixtures/test_sentencepiece.model") __UpperCamelCase : Any = {"target_lang": "fi", "source_lang": "en"} __UpperCamelCase : Optional[int] = ">>zh<<" __UpperCamelCase : List[Any] = "Helsinki-NLP/" if is_torch_available(): __UpperCamelCase : str = "pt" elif is_tf_available(): __UpperCamelCase : Union[str, Any] = "tf" else: __UpperCamelCase : int = "jax" @require_sentencepiece class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = MarianTokenizer UpperCamelCase__ = False UpperCamelCase__ = True def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().setUp() a = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] a = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) a = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["""vocab"""] ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["""source_spm"""] ) copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["""target_spm"""] ) a = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self :Any , **__magic_name__ :str ): '''simple docstring''' return MarianTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def lowerCamelCase__ ( self :Dict , __magic_name__ :List[Any] ): '''simple docstring''' return ( "This is a test", "This is a test", ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = """</s>""" a = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<pad>""" ) self.assertEqual(len(__magic_name__ ) , 9 ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = MarianTokenizer.from_pretrained(F'{ORG_NAME}opus-mt-en-de' ) a = en_de_tokenizer(["""I am a small frog"""] , return_tensors=__magic_name__ ) self.assertIsInstance(__magic_name__ , __magic_name__ ) a = [38, 121, 14, 697, 3_8848, 0] self.assertListEqual(__magic_name__ , batch.input_ids[0] ) a = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(__magic_name__ ) a = [x.name for x in Path(__magic_name__ ).glob("""*""" )] self.assertIn("""source.spm""" , __magic_name__ ) MarianTokenizer.from_pretrained(__magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = self.get_tokenizer() a = tok( ["""I am a small frog""" * 1000, """I am a small frog"""] , padding=__magic_name__ , truncation=__magic_name__ , return_tensors=__magic_name__ ) self.assertIsInstance(__magic_name__ , __magic_name__ ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizer() a = tok(["""I am a tiny frog""", """I am a small frog"""] , padding=__magic_name__ , return_tensors=__magic_name__ ) self.assertIsInstance(__magic_name__ , __magic_name__ ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = {"""input_ids""": [[4_3495, 462, 20, 4_2164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 3_8999, 6, 8, 464, 132, 1703, 492, 13, 4669, 3_7867, 13, 7525, 27, 1593, 988, 13, 3_3972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 1_2338, 2, 1_3958, 387, 2, 3629, 6953, 188, 2900, 2, 1_3958, 8011, 1_1501, 23, 8460, 4073, 3_4009, 20, 435, 1_1439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 3_7867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 2_6453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 1_0767, 6, 316, 304, 4239, 3, 0], [148, 1_5722, 19, 1839, 12, 1350, 13, 2_2327, 5082, 5418, 4_7567, 3_5938, 59, 318, 1_9552, 108, 2183, 54, 1_4976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 1_9088, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100], [36, 6395, 1_2570, 3_9147, 1_1597, 6, 266, 4, 4_5405, 7296, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name="""Helsinki-NLP/opus-mt-en-de""" , revision="""1a8c2263da11e68e50938f97e10cd57820bd504c""" , decode_kwargs={"""use_source_tokenizer""": True} , ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs""" ) a = """Tämä on testi""" a = """This is a test""" a = [76, 7, 2047, 2] a = [69, 12, 11, 940, 2] a = tokenizer(__magic_name__ ).input_ids self.assertListEqual(__magic_name__ , __magic_name__ ) a = tokenizer(text_target=__magic_name__ ).input_ids self.assertListEqual(__magic_name__ , __magic_name__ ) a = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ )
347
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :List[str] , __magic_name__ :int="</s>" , __magic_name__ :List[Any]="<unk>" , __magic_name__ :Optional[Any]="<pad>" , __magic_name__ :Optional[int]=125 , __magic_name__ :List[str]=None , **__magic_name__ :List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: a = [F'<extra_id_{i}>' for i in range(__magic_name__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens a = len(set(filter(lambda __magic_name__ : bool("""extra_id""" in str(__magic_name__ ) ) , __magic_name__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to ByT5Tokenizer. In this case the additional_special_tokens must include the""" """ extra_ids tokens""" ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token super().__init__( eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , extra_ids=__magic_name__ , additional_special_tokens=__magic_name__ , **__magic_name__ , ) a = extra_ids a = 2**8 # utf is 8 bits # define special tokens dict a = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } a = len(self.special_tokens_encoder ) a = len(__magic_name__ ) for i, token in enumerate(__magic_name__ ): a = self.vocab_size + i - n a = {v: k for k, v in self.special_tokens_encoder.items()} @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def lowerCamelCase__ ( self :Any , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None , __magic_name__ :bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__magic_name__ )) + [1] return ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def lowerCamelCase__ ( self :str , __magic_name__ :List[int] ): '''simple docstring''' if len(__magic_name__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = self._add_eos_if_not_present(__magic_name__ ) if token_ids_a is None: return token_ids_a else: a = self._add_eos_if_not_present(__magic_name__ ) return token_ids_a + token_ids_a def lowerCamelCase__ ( self :List[str] , __magic_name__ :str ): '''simple docstring''' a = [chr(__magic_name__ ) for i in text.encode("""utf-8""" )] return tokens def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if token in self.special_tokens_encoder: a = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: a = self.added_tokens_encoder[token] elif len(__magic_name__ ) != 1: a = self.unk_token_id else: a = ord(__magic_name__ ) + self._num_special_tokens return token_id def lowerCamelCase__ ( self :List[str] , __magic_name__ :Dict ): '''simple docstring''' if index in self.special_tokens_decoder: a = self.special_tokens_decoder[index] else: a = chr(index - self._num_special_tokens ) return token def lowerCamelCase__ ( self :Tuple , __magic_name__ :Optional[int] ): '''simple docstring''' a = b"""""" for token in tokens: if token in self.special_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.added_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.special_tokens_encoder: a = token.encode("""utf-8""" ) elif token in self.added_tokens_encoder: a = token.encode("""utf-8""" ) else: a = bytes([ord(__magic_name__ )] ) bstring += tok_string a = bstring.decode("""utf-8""" , errors="""ignore""" ) return string def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :str , __magic_name__ :Optional[str] = None ): '''simple docstring''' return ()
347
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : str = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.linear_k": "encoder.layers.*.self_attn.linear_k", "self_attn.linear_v": "encoder.layers.*.self_attn.linear_v", "self_attn.linear_q": "encoder.layers.*.self_attn.linear_q", "self_attn.pos_bias_u": "encoder.layers.*.self_attn.pos_bias_u", "self_attn.pos_bias_v": "encoder.layers.*.self_attn.pos_bias_v", "self_attn.linear_out": "encoder.layers.*.self_attn.linear_out", "self_attn.linear_pos": "encoder.layers.*.self_attn.linear_pos", "self_attn.rotary_emb": "encoder.embed_positions", "self_attn_layer_norm": "encoder.layers.*.self_attn_layer_norm", "conv_module.pointwise_conv1": "encoder.layers.*.conv_module.pointwise_conv1", "conv_module.pointwise_conv2": "encoder.layers.*.conv_module.pointwise_conv2", "conv_module.depthwise_conv": "encoder.layers.*.conv_module.depthwise_conv", "conv_module.batch_norm": "encoder.layers.*.conv_module.batch_norm", "conv_module.layer_norm": "encoder.layers.*.conv_module.layer_norm", "ffn1.w_1": "encoder.layers.*.ffn1.intermediate_dense", "ffn1.w_2": "encoder.layers.*.ffn1.output_dense", "ffn1.layer_norm": "encoder.layers.*.ffn1_layer_norm", "ffn2.w_1": "encoder.layers.*.ffn2.intermediate_dense", "ffn2.w_2": "encoder.layers.*.ffn2.output_dense", "ffn2.layer_norm": "encoder.layers.*.ffn2_layer_norm", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } __UpperCamelCase : str = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: for attribute in key.split(""".""" ): a = getattr(__lowerCamelCase , __lowerCamelCase ) if weight_type is not None: a = getattr(__lowerCamelCase , __lowerCamelCase ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value elif weight_type == "running_mean": a = value elif weight_type == "running_var": a = value elif weight_type == "num_batches_tracked": a = value elif weight_type == "inv_freq": a = value else: a = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Tuple: a = [] a = fairseq_model.state_dict() a = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) a = True else: for key, mapped_key in MAPPING.items(): a = """wav2vec2_conformer.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: a = True if "*" in mapped_key: a = name.split(__lowerCamelCase )[0].split(""".""" )[-2] a = mapped_key.replace("""*""" , __lowerCamelCase ) if "pos_bias_u" in name: a = None elif "pos_bias_v" in name: a = None elif "weight_g" in name: a = """weight_g""" elif "weight_v" in name: a = """weight_v""" elif "bias" in name: a = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj a = """weight""" elif "running_mean" in name: a = """running_mean""" elif "inv_freq" in name: a = """inv_freq""" elif "running_var" in name: a = """running_var""" elif "num_batches_tracked" in name: a = """num_batches_tracked""" else: a = None set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(f'Unused weights: {unused_weights}' ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Tuple: a = full_name.split("""conv_layers.""" )[-1] a = name.split(""".""" ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) a = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) a = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.' ) a = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.' ) a = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) @torch.no_grad() def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=True ) -> Optional[int]: if config_path is not None: a = WavaVecaConformerConfig.from_pretrained(__lowerCamelCase , hidden_act="""swish""" ) else: a = WavaVecaConformerConfig() if "rope" in checkpoint_path: a = """rotary""" if is_finetuned: if dict_path: a = Dictionary.load(__lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq a = target_dict.pad_index a = target_dict.bos_index a = target_dict.eos_index a = len(target_dict.symbols ) a = os.path.join(__lowerCamelCase , """vocab.json""" ) if not os.path.isdir(__lowerCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__lowerCamelCase ) ) return os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) a = target_dict.indices # fairseq has the <pad> and <s> switched a = 0 a = 1 with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(__lowerCamelCase , __lowerCamelCase ) a = WavaVecaCTCTokenizer( __lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=__lowerCamelCase , ) a = True if config.feat_extract_norm == """layer""" else False a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) a = WavaVecaProcessor(feature_extractor=__lowerCamelCase , tokenizer=__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) a = WavaVecaConformerForCTC(__lowerCamelCase ) else: a = WavaVecaConformerForPreTraining(__lowerCamelCase ) if is_finetuned: a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: a = argparse.Namespace(task="""audio_pretraining""" ) a = fairseq.tasks.setup_task(__lowerCamelCase ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__lowerCamelCase ) a = model[0].eval() recursively_load_weights(__lowerCamelCase , __lowerCamelCase , not is_finetuned ) hf_wavavec.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": __UpperCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) __UpperCamelCase : Optional[Any] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
347
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __lowerCAmelCase : def __init__( self :Optional[int] , __magic_name__ :str , __magic_name__ :int=2 , __magic_name__ :List[str]=3 , __magic_name__ :Optional[int]=4 , __magic_name__ :str=2 , __magic_name__ :Any=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Dict=True , __magic_name__ :List[Any]=99 , __magic_name__ :Dict=36 , __magic_name__ :Optional[Any]=3 , __magic_name__ :str=4 , __magic_name__ :Optional[Any]=37 , __magic_name__ :Dict="gelu" , __magic_name__ :Any=0.1 , __magic_name__ :Union[str, Any]=0.1 , __magic_name__ :Dict=512 , __magic_name__ :str=16 , __magic_name__ :List[Any]=2 , __magic_name__ :Tuple=0.02 , __magic_name__ :Any=6 , __magic_name__ :Optional[int]=6 , __magic_name__ :Tuple=3 , __magic_name__ :str=4 , __magic_name__ :List[str]=None , __magic_name__ :str=1000 , ): '''simple docstring''' a = parent a = batch_size a = num_channels a = image_size a = patch_size a = text_seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = coordinate_size a = shape_size a = num_labels a = num_choices a = scope a = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) a = text_seq_length a = (image_size // patch_size) ** 2 + 1 a = self.text_seq_length + self.image_seq_length def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) a = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a = bbox[i, j, 3] a = bbox[i, j, 1] a = t if bbox[i, j, 2] < bbox[i, j, 0]: a = bbox[i, j, 2] a = bbox[i, j, 0] a = t a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.text_seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) a = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def lowerCamelCase__ ( self :int , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :List[str] , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int ): '''simple docstring''' a = LayoutLMvaModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # text + image a = model(__magic_name__ , pixel_values=__magic_name__ ) a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only a = model(__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only a = model(pixel_values=__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :List[Any] , __magic_name__ :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Union[str, Any] , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :List[str] , __magic_name__ :List[str] ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Dict , __magic_name__ :Optional[Any] , __magic_name__ :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :int , __magic_name__ :List[str] , __magic_name__ :Tuple ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :str , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :str , __magic_name__ :List[str] , __magic_name__ :Optional[int] , __magic_name__ :Optional[Any] ): '''simple docstring''' a = LayoutLMvaForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase__ = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :Optional[Any] , __magic_name__ :List[str] , __magic_name__ :List[Any] ): '''simple docstring''' return True def lowerCamelCase__ ( self :int ): '''simple docstring''' a = LayoutLMvaModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :Any=False ): '''simple docstring''' a = copy.deepcopy(__magic_name__ ) if model_class in get_values(__magic_name__ ): a = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__magic_name__ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__magic_name__ ): a = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in get_values(__magic_name__ ): a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__magic_name__ , ) return inputs_dict def lowerCamelCase__ ( self :str ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a = type self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def lowerCamelCase__ ( self :int ): '''simple docstring''' for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = LayoutLMvaModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def __A ( ) -> str: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__magic_name__ ) if is_vision_available() else None @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(__magic_name__ ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__magic_name__ , return_tensors="""pt""" ).pixel_values.to(__magic_name__ ) a = torch.tensor([[1, 2]] ) a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass a = model( input_ids=input_ids.to(__magic_name__ ) , bbox=bbox.to(__magic_name__ ) , pixel_values=pixel_values.to(__magic_name__ ) , ) # verify the logits a = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __magic_name__ ) a = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
from math import factorial def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> float: if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) a = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! a = float(factorial(__lowerCamelCase ) ) coefficient /= factorial(__lowerCamelCase ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("Probability of 2 successes out of 4 trails") print("with probability of 0.75 is:", end=" ") print(binomial_distribution(2, 4, 0.75))
347
from copy import deepcopy class __lowerCAmelCase : def __init__( self :Union[str, Any] , __magic_name__ :list[int] | None = None , __magic_name__ :int | None = None ): '''simple docstring''' if arr is None and size is not None: a = size a = [0] * size elif arr is not None: self.init(__magic_name__ ) else: raise ValueError("""Either arr or size must be specified""" ) def lowerCamelCase__ ( self :Dict , __magic_name__ :list[int] ): '''simple docstring''' a = len(__magic_name__ ) a = deepcopy(__magic_name__ ) for i in range(1 , self.size ): a = self.next_(__magic_name__ ) if j < self.size: self.tree[j] += self.tree[i] def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): a = self.next_(__magic_name__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index + (index & (-index)) @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index - (index & (-index)) def lowerCamelCase__ ( self :Any , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value a = self.next_(__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' self.add(__magic_name__ , value - self.get(__magic_name__ ) ) def lowerCamelCase__ ( self :int , __magic_name__ :int ): '''simple docstring''' if right == 0: return 0 a = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] a = self.prev(__magic_name__ ) return result def lowerCamelCase__ ( self :int , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' return self.prefix(__magic_name__ ) - self.prefix(__magic_name__ ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :int ): '''simple docstring''' return self.query(__magic_name__ , index + 1 ) def lowerCamelCase__ ( self :Dict , __magic_name__ :int ): '''simple docstring''' value -= self.tree[0] if value < 0: return -1 a = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 a = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
347
1
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch __UpperCamelCase : int = True except ImportError: __UpperCamelCase : Dict = False try: from torch.hub import _get_torch_home __UpperCamelCase : Any = _get_torch_home() except ImportError: __UpperCamelCase : Any = os.path.expanduser( os.getenv("TORCH_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "torch")) ) __UpperCamelCase : Optional[int] = os.path.join(torch_cache_home, "transformers") __UpperCamelCase : Any = "https://cdn.huggingface.co" __UpperCamelCase : int = "https://s3.amazonaws.com/models.huggingface.co/bert" __UpperCamelCase : Optional[Any] = "/".join(str(Path(__file__).resolve()).split("/")[:-1]) __UpperCamelCase : Optional[Any] = os.path.join(PATH, "config.yaml") __UpperCamelCase : Any = os.path.join(PATH, "attributes.txt") __UpperCamelCase : Union[str, Any] = os.path.join(PATH, "objects.txt") __UpperCamelCase : Union[str, Any] = os.getenv("PYTORCH_PRETRAINED_BERT_CACHE", default_cache_path) __UpperCamelCase : List[str] = os.getenv("PYTORCH_TRANSFORMERS_CACHE", PYTORCH_PRETRAINED_BERT_CACHE) __UpperCamelCase : Dict = os.getenv("TRANSFORMERS_CACHE", PYTORCH_TRANSFORMERS_CACHE) __UpperCamelCase : List[Any] = "pytorch_model.bin" __UpperCamelCase : List[Any] = "config.yaml" def __A ( __lowerCamelCase=OBJECTS , __lowerCamelCase=ATTRIBUTES ) -> Dict: a = [] with open(__lowerCamelCase ) as f: for object in f.readlines(): vg_classes.append(object.split(""",""" )[0].lower().strip() ) a = [] with open(__lowerCamelCase ) as f: for object in f.readlines(): vg_attrs.append(object.split(""",""" )[0].lower().strip() ) return vg_classes, vg_attrs def __A ( __lowerCamelCase ) -> List[str]: a = OrderedDict() with open(__lowerCamelCase , """rb""" ) as f: a = pkl.load(__lowerCamelCase )["""model"""] for k in copy.deepcopy(list(ckp.keys() ) ): a = ckp.pop(__lowerCamelCase ) if isinstance(__lowerCamelCase , np.ndarray ): a = torch.tensor(__lowerCamelCase ) else: assert isinstance(__lowerCamelCase , torch.tensor ), type(__lowerCamelCase ) a = v return r class __lowerCAmelCase : UpperCamelCase__ = {} def __init__( self :Optional[int] , __magic_name__ :dict , __magic_name__ :str = "root" , __magic_name__ :List[str]=0 ): '''simple docstring''' a = name a = level a = {} for k, v in dictionary.items(): if v is None: raise ValueError() a = copy.deepcopy(__magic_name__ ) a = copy.deepcopy(__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ): a = Config(__magic_name__ , name=__magic_name__ , level=level + 1 ) a = v setattr(self , __magic_name__ , __magic_name__ ) a = d def __repr__( self :int ): '''simple docstring''' return str(list((self._pointer.keys()) ) ) def __setattr__( self :Any , __magic_name__ :Tuple , __magic_name__ :List[str] ): '''simple docstring''' a = val a = val a = key.split(""".""" ) a = len(__magic_name__ ) - 1 a = self._pointer if len(__magic_name__ ) > 1: for i, l in enumerate(__magic_name__ ): if hasattr(self , __magic_name__ ) and isinstance(getattr(self , __magic_name__ ) , __magic_name__ ): setattr(getattr(self , __magic_name__ ) , """.""".join(levels[i:] ) , __magic_name__ ) if l == last_level: a = val else: a = pointer[l] def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return self._pointer def lowerCamelCase__ ( self :List[Any] , __magic_name__ :Union[str, Any] , __magic_name__ :Optional[Any] ): '''simple docstring''' with open(F'{file_name}' , """w""" ) as stream: dump(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Any , __magic_name__ :Dict , __magic_name__ :Optional[Any] ): '''simple docstring''' with open(F'{file_name}' , """w""" ) as stream: json.dump(__magic_name__ , __magic_name__ ) @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' with open(__magic_name__ ) as stream: a = load(__magic_name__ , Loader=__magic_name__ ) return data def __str__( self :List[str] ): '''simple docstring''' a = """ """ if self._name != "root": a = F'{t * (self._level-1)}{self._name}:\n' else: a = """""" a = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(__magic_name__ , __magic_name__ ): r += F'{t * (self._level)}{v}\n' self._level += 1 else: r += F'{t * (self._level)}{k}: {v} ({type(__magic_name__ ).__name__})\n' a = level return r[:-1] @classmethod def lowerCamelCase__ ( cls :Union[str, Any] , __magic_name__ :str , **__magic_name__ :Dict ): '''simple docstring''' a , a = cls.get_config_dict(__magic_name__ , **__magic_name__ ) return cls(__magic_name__ ) @classmethod def lowerCamelCase__ ( cls :int , __magic_name__ :str , **__magic_name__ :Union[str, Any] ): '''simple docstring''' a = kwargs.pop("""cache_dir""" , __magic_name__ ) a = kwargs.pop("""force_download""" , __magic_name__ ) a = kwargs.pop("""resume_download""" , __magic_name__ ) a = kwargs.pop("""proxies""" , __magic_name__ ) a = kwargs.pop("""local_files_only""" , __magic_name__ ) if os.path.isdir(__magic_name__ ): a = os.path.join(__magic_name__ , __magic_name__ ) elif os.path.isfile(__magic_name__ ) or is_remote_url(__magic_name__ ): a = pretrained_model_name_or_path else: a = hf_bucket_url(__magic_name__ , filename=__magic_name__ , use_cdn=__magic_name__ ) try: # Load from URL or cache if already cached a = cached_path( __magic_name__ , cache_dir=__magic_name__ , force_download=__magic_name__ , proxies=__magic_name__ , resume_download=__magic_name__ , local_files_only=__magic_name__ , ) # Load config dict if resolved_config_file is None: raise EnvironmentError a = Config.load_yaml(__magic_name__ ) except EnvironmentError: a = """Can't load config for""" raise EnvironmentError(__magic_name__ ) if resolved_config_file == config_file: print("""loading configuration file from path""" ) else: print("""loading configuration file cache""" ) return Config.load_yaml(__magic_name__ ), kwargs def __A ( __lowerCamelCase ) -> Any: a = torch.load("""dump.pt""" , map_location=in_tensor.device ) a = in_tensor.numpy() a = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(__lowerCamelCase , __lowerCamelCase , rtol=0.01 , atol=0.1 ), ( f'{sum([1 for x in np.isclose(__lowerCamelCase , __lowerCamelCase , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %' " element-wise mismatch" ) raise Exception("""tensors are all good""" ) # Hugging face functions below def __A ( __lowerCamelCase ) -> Union[str, Any]: a = urlparse(__lowerCamelCase ) return parsed.scheme in ("http", "https") def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=True ) -> str: a = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX a = """/""" not in model_id if legacy_format: return f'{endpoint}/{model_id}-{filename}' else: return f'{endpoint}/{model_id}/{filename}' def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=0 , __lowerCamelCase=None , ) -> List[str]: a = """python/{}""".format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(__lowerCamelCase , __lowerCamelCase ): ua += "; " + "; ".join("""{}/{}""".format(__lowerCamelCase , __lowerCamelCase ) for k, v in user_agent.items() ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): ua += "; " + user_agent a = {"""user-agent""": ua} if resume_size > 0: a = """bytes=%d-""" % (resume_size,) a = requests.get(__lowerCamelCase , stream=__lowerCamelCase , proxies=__lowerCamelCase , headers=__lowerCamelCase ) if response.status_code == 416: # Range not satisfiable return a = response.headers.get("""Content-Length""" ) a = resume_size + int(__lowerCamelCase ) if content_length is not None else None a = tqdm( unit="""B""" , unit_scale=__lowerCamelCase , total=__lowerCamelCase , initial=__lowerCamelCase , desc="""Downloading""" , ) for chunk in response.iter_content(chunk_size=1024 ): if chunk: # filter out keep-alive new chunks progress.update(len(__lowerCamelCase ) ) temp_file.write(__lowerCamelCase ) progress.close() def __A ( __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=False , __lowerCamelCase=None , __lowerCamelCase=10 , __lowerCamelCase=False , __lowerCamelCase=None , __lowerCamelCase=False , ) -> Optional[int]: if cache_dir is None: a = TRANSFORMERS_CACHE if isinstance(__lowerCamelCase , __lowerCamelCase ): a = str(__lowerCamelCase ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) a = None if not local_files_only: try: a = requests.head(__lowerCamelCase , allow_redirects=__lowerCamelCase , proxies=__lowerCamelCase , timeout=__lowerCamelCase ) if response.status_code == 200: a = response.headers.get("""ETag""" ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass a = url_to_filename(__lowerCamelCase , __lowerCamelCase ) # get cache path to put the file a = os.path.join(__lowerCamelCase , __lowerCamelCase ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(__lowerCamelCase ): return cache_path else: a = [ file for file in fnmatch.filter(os.listdir(__lowerCamelCase ) , filename + """.*""" ) if not file.endswith(""".json""" ) and not file.endswith(""".lock""" ) ] if len(__lowerCamelCase ) > 0: return os.path.join(__lowerCamelCase , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( """Cannot find the requested files in the cached path and outgoing traffic has been""" """ disabled. To enable model look-ups and downloads online, set 'local_files_only'""" """ to False.""" ) return None # From now on, etag is not None. if os.path.exists(__lowerCamelCase ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. a = cache_path + """.lock""" with FileLock(__lowerCamelCase ): # If the download just completed while the lock was activated. if os.path.exists(__lowerCamelCase ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: a = cache_path + """.incomplete""" @contextmanager def _resumable_file_manager(): with open(__lowerCamelCase , """a+b""" ) as f: yield f a = _resumable_file_manager if os.path.exists(__lowerCamelCase ): a = os.stat(__lowerCamelCase ).st_size else: a = 0 else: a = partial(tempfile.NamedTemporaryFile , dir=__lowerCamelCase , delete=__lowerCamelCase ) a = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( """%s not found in cache or force_download set to True, downloading to %s""" , __lowerCamelCase , temp_file.name , ) http_get( __lowerCamelCase , __lowerCamelCase , proxies=__lowerCamelCase , resume_size=__lowerCamelCase , user_agent=__lowerCamelCase , ) os.replace(temp_file.name , __lowerCamelCase ) a = {"""url""": url, """etag""": etag} a = cache_path + """.json""" with open(__lowerCamelCase , """w""" ) as meta_file: json.dump(__lowerCamelCase , __lowerCamelCase ) return cache_path def __A ( __lowerCamelCase , __lowerCamelCase=None ) -> List[str]: a = url.encode("""utf-8""" ) a = shaaaa(__lowerCamelCase ) a = url_hash.hexdigest() if etag: a = etag.encode("""utf-8""" ) a = shaaaa(__lowerCamelCase ) filename += "." + etag_hash.hexdigest() if url.endswith(""".h5""" ): filename += ".h5" return filename def __A ( __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=False , __lowerCamelCase=None , __lowerCamelCase=False , __lowerCamelCase=None , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False , ) -> Union[str, Any]: if cache_dir is None: a = TRANSFORMERS_CACHE if isinstance(__lowerCamelCase , __lowerCamelCase ): a = str(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): a = str(__lowerCamelCase ) if is_remote_url(__lowerCamelCase ): # URL, so get it from the cache (downloading if necessary) a = get_from_cache( __lowerCamelCase , cache_dir=__lowerCamelCase , force_download=__lowerCamelCase , proxies=__lowerCamelCase , resume_download=__lowerCamelCase , user_agent=__lowerCamelCase , local_files_only=__lowerCamelCase , ) elif os.path.exists(__lowerCamelCase ): # File, and it exists. a = url_or_filename elif urlparse(__lowerCamelCase ).scheme == "": # File, but it doesn't exist. raise EnvironmentError("""file {} not found""".format(__lowerCamelCase ) ) else: # Something unknown raise ValueError("""unable to parse {} as a URL or as a local path""".format(__lowerCamelCase ) ) if extract_compressed_file: if not is_zipfile(__lowerCamelCase ) and not tarfile.is_tarfile(__lowerCamelCase ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" a , a = os.path.split(__lowerCamelCase ) a = output_file.replace(""".""" , """-""" ) + """-extracted""" a = os.path.join(__lowerCamelCase , __lowerCamelCase ) if os.path.isdir(__lowerCamelCase ) and os.listdir(__lowerCamelCase ) and not force_extract: return output_path_extracted # Prevent parallel extractions a = output_path + """.lock""" with FileLock(__lowerCamelCase ): shutil.rmtree(__lowerCamelCase , ignore_errors=__lowerCamelCase ) os.makedirs(__lowerCamelCase ) if is_zipfile(__lowerCamelCase ): with ZipFile(__lowerCamelCase , """r""" ) as zip_file: zip_file.extractall(__lowerCamelCase ) zip_file.close() elif tarfile.is_tarfile(__lowerCamelCase ): a = tarfile.open(__lowerCamelCase ) tar_file.extractall(__lowerCamelCase ) tar_file.close() else: raise EnvironmentError("""Archive format of {} could not be identified""".format(__lowerCamelCase ) ) return output_path_extracted return output_path def __A ( __lowerCamelCase , __lowerCamelCase="," ) -> Optional[Any]: assert isinstance(__lowerCamelCase , __lowerCamelCase ) if os.path.isfile(__lowerCamelCase ): with open(__lowerCamelCase ) as f: a = eval(f.read() ) else: a = requests.get(__lowerCamelCase ) try: a = requests.json() except Exception: a = req.content.decode() assert data is not None, "could not connect" try: a = eval(__lowerCamelCase ) except Exception: a = data.split("""\n""" ) req.close() return data def __A ( __lowerCamelCase ) -> Any: a = requests.get(__lowerCamelCase ) a = np.array(Image.open(BytesIO(response.content ) ) ) return img def __A ( __lowerCamelCase ) -> List[str]: a = url.split("""/""" )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(__lowerCamelCase ) with open(__lowerCamelCase , """rb""" ) as stream: a = pkl.load(__lowerCamelCase ) a = weights.pop("""model""" ) a = {} for k, v in model.items(): a = torch.from_numpy(__lowerCamelCase ) if "running_var" in k: a = torch.tensor([0] ) a = k.replace("""running_var""" , """num_batches_tracked""" ) a = zero return new def __A ( ) -> str: print(f'{os.path.abspath(os.path.join(__lowerCamelCase , os.pardir ) )}/demo.ipynb' ) def __A ( __lowerCamelCase , __lowerCamelCase="RGB" ) -> List[Any]: assert isinstance(__lowerCamelCase , __lowerCamelCase ) if os.path.isfile(__lowerCamelCase ): a = cva.imread(__lowerCamelCase ) else: a = get_image_from_url(__lowerCamelCase ) assert img is not None, f'could not connect to: {im}' a = cva.cvtColor(__lowerCamelCase , cva.COLOR_BGR2RGB ) if input_format == "RGB": a = img[:, :, ::-1] return img def __A ( __lowerCamelCase , __lowerCamelCase=1 ) -> List[str]: return (images[i : i + batch] for i in range(0 , len(__lowerCamelCase ) , __lowerCamelCase ))
347
from __future__ import annotations from typing import Generic, TypeVar __UpperCamelCase : Union[str, Any] = TypeVar("T") class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple , __magic_name__ :T ): '''simple docstring''' a = data a = self a = 0 class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T ): '''simple docstring''' a = DisjointSetTreeNode(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :T ): '''simple docstring''' a = self.map[data] if elem_ref != elem_ref.parent: a = self.find_set(elem_ref.parent.data ) return elem_ref.parent def lowerCamelCase__ ( self :List[Any] , __magic_name__ :DisjointSetTreeNode[T] , __magic_name__ :DisjointSetTreeNode[T] ): '''simple docstring''' if nodea.rank > nodea.rank: a = nodea else: a = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T , __magic_name__ :T ): '''simple docstring''' self.link(self.find_set(__magic_name__ ) , self.find_set(__magic_name__ ) ) class __lowerCAmelCase ( Generic[T] ): def __init__( self :Union[str, Any] ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :T ): '''simple docstring''' if node not in self.connections: a = {} def lowerCamelCase__ ( self :Any , __magic_name__ :T , __magic_name__ :T , __magic_name__ :int ): '''simple docstring''' self.add_node(__magic_name__ ) self.add_node(__magic_name__ ) a = weight a = weight def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] a = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda __magic_name__ : x[2] ) # creating the disjoint set a = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__magic_name__ ) # MST generation a = 0 a = 0 a = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: a , a , a = edges[index] index += 1 a = disjoint_set.find_set(__magic_name__ ) a = disjoint_set.find_set(__magic_name__ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__magic_name__ , __magic_name__ , __magic_name__ ) disjoint_set.union(__magic_name__ , __magic_name__ ) return graph
347
1
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :str , __magic_name__ :List[str] , __magic_name__ :List[Any]=3 , __magic_name__ :Dict=32 , __magic_name__ :Optional[Any]=3 , __magic_name__ :Dict=10 , __magic_name__ :List[Any]=[10, 20, 30, 40] , __magic_name__ :Dict=[1, 1, 2, 1] , __magic_name__ :Dict=True , __magic_name__ :Tuple=True , __magic_name__ :Optional[Any]="relu" , __magic_name__ :Optional[int]=3 , __magic_name__ :List[Any]=None , ): '''simple docstring''' a = parent a = batch_size a = image_size a = num_channels a = embeddings_size a = hidden_sizes a = depths a = is_training a = use_labels a = hidden_act a = num_labels a = scope a = len(__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = self.get_config() return config, pixel_values def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Any , __magic_name__ :str ): '''simple docstring''' a = FlaxRegNetModel(config=__magic_name__ ) a = model(__magic_name__ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCamelCase__ ( self :Dict , __magic_name__ :Optional[Any] , __magic_name__ :Tuple ): '''simple docstring''' a = self.num_labels a = FlaxRegNetForImageClassification(config=__magic_name__ ) a = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a = config_and_inputs a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = FlaxRegNetModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCamelCase__ ( self :Any ): '''simple docstring''' return def lowerCamelCase__ ( self :str ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' pass def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' def check_hidden_states_output(__magic_name__ :str , __magic_name__ :Optional[int] , __magic_name__ :Optional[int] ): a = model_class(__magic_name__ ) a = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__magic_name__ ) , expected_num_stages + 1 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = True check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = model_class(__magic_name__ ) @jax.jit def model_jitted(__magic_name__ :Dict , **__magic_name__ :Union[str, Any] ): return model(pixel_values=__magic_name__ , **__magic_name__ ) with self.subTest("""JIT Enabled""" ): a = model_jitted(**__magic_name__ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): a = model_jitted(**__magic_name__ ).to_tuple() self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) ) for jitted_output, output in zip(__magic_name__ , __magic_name__ ): self.assertEqual(jitted_output.shape , output.shape ) def __A ( ) -> str: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_flax class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :str ): '''simple docstring''' return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040""" ) if is_vision_available() else None @slow def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040""" ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__magic_name__ , return_tensors="""np""" ) a = model(**__magic_name__ ) # verify the logits a = (1, 1000) self.assertEqual(outputs.logits.shape , __magic_name__ ) a = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __magic_name__ , atol=1E-4 ) )
347
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = tempfile.mkdtemp() a = BlipImageProcessor() a = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) a = BlipProcessor(__magic_name__ , __magic_name__ ) processor.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self :List[Any] , **__magic_name__ :Union[str, Any] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).tokenizer def lowerCamelCase__ ( self :str , **__magic_name__ :List[str] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).image_processor def lowerCamelCase__ ( self :int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__magic_name__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) a = self.get_image_processor(do_normalize=__magic_name__ , padding_value=1.0 ) a = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__magic_name__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __magic_name__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = self.prepare_image_inputs() a = image_processor(__magic_name__ , return_tensors="""np""" ) a = processor(images=__magic_name__ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = processor(text=__magic_name__ ) a = tokenizer(__magic_name__ , return_token_type_ids=__magic_name__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(__magic_name__ ): processor() def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__magic_name__ ) a = tokenizer.batch_decode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
347
1
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class __lowerCAmelCase ( __magic_name__ ): def __init__( self :str , __magic_name__ :Any , __magic_name__ :Union[str, Any] , __magic_name__ :Tuple ): '''simple docstring''' a = dataset a = process a = params def __len__( self :int ): '''simple docstring''' return len(self.dataset ) def __getitem__( self :Union[str, Any] , __magic_name__ :Union[str, Any] ): '''simple docstring''' a = self.dataset[i] a = self.process(__magic_name__ , **self.params ) return processed class __lowerCAmelCase ( __magic_name__ ): def __init__( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Dict , __magic_name__ :str , __magic_name__ :int=None ): '''simple docstring''' a = loader a = infer a = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether a = None a = loader_batch_size # Internal bookkeeping a = None a = None def __len__( self :List[Any] ): '''simple docstring''' return len(self.loader ) def __iter__( self :Any ): '''simple docstring''' a = iter(self.loader ) return self def lowerCamelCase__ ( self :int ): '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice a = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) a = {} for k, element in self._loader_batch_data.items(): if isinstance(__magic_name__ , __magic_name__ ): # Convert ModelOutput to tuple first a = element.to_tuple() if isinstance(element[0] , torch.Tensor ): a = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): a = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(__magic_name__ , __magic_name__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): a = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): a = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around a = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers a = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers a = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. a = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 a = self._loader_batch_data.__class__(__magic_name__ ) self._loader_batch_index += 1 return result def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch a = next(self.iterator ) a = self.infer(__magic_name__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(__magic_name__ , torch.Tensor ): a = processed else: a = list(processed.keys() )[0] a = processed[key] if isinstance(__magic_name__ , __magic_name__ ): a = len(__magic_name__ ) else: a = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. a = observed_batch_size # Setting internal index to unwrap the batch a = processed a = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class __lowerCAmelCase ( __magic_name__ ): def __init__( self :Dict , __magic_name__ :int , __magic_name__ :Any , __magic_name__ :Tuple , __magic_name__ :List[str]=None ): '''simple docstring''' super().__init__(__magic_name__ , __magic_name__ , __magic_name__ ) def __iter__( self :int ): '''simple docstring''' a = iter(self.loader ) a = None return self def lowerCamelCase__ ( self :Any ): '''simple docstring''' if self.subiterator is None: a = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item a = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators a = self.infer(next(self.iterator ) , **self.params ) a = next(self.subiterator ) return processed class __lowerCAmelCase ( __magic_name__ ): def __iter__( self :Optional[Any] ): '''simple docstring''' a = iter(self.loader ) return self def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = False a = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: a = self.loader_batch_item() a = item.pop("""is_last""" ) accumulator.append(__magic_name__ ) if is_last: return accumulator while not is_last: a = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(__magic_name__ , torch.Tensor ): a = processed else: a = list(processed.keys() )[0] a = processed[key] if isinstance(__magic_name__ , __magic_name__ ): a = len(__magic_name__ ) else: a = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. a = observed_batch_size a = processed a = 0 while self._loader_batch_index < self.loader_batch_size: a = self.loader_batch_item() a = item.pop("""is_last""" ) accumulator.append(__magic_name__ ) if is_last: return accumulator else: a = processed a = item.pop("""is_last""" ) accumulator.append(__magic_name__ ) return accumulator class __lowerCAmelCase ( __magic_name__ ): def __init__( self :Any , __magic_name__ :Dataset , __magic_name__ :str ): '''simple docstring''' a = dataset a = key def __len__( self :Tuple ): '''simple docstring''' return len(self.dataset ) def __getitem__( self :Union[str, Any] , __magic_name__ :Optional[Any] ): '''simple docstring''' return self.dataset[i][self.key] class __lowerCAmelCase ( __magic_name__ ): def __init__( self :List[Any] , __magic_name__ :Dataset , __magic_name__ :str , __magic_name__ :str ): '''simple docstring''' a = dataset a = keya a = keya def __len__( self :Union[str, Any] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self :Optional[Any] , __magic_name__ :Tuple ): '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
347
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : int = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class __lowerCAmelCase ( __magic_name__ , __magic_name__ ): UpperCamelCase__ = '''nat''' UpperCamelCase__ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self :Any , __magic_name__ :int=4 , __magic_name__ :Dict=3 , __magic_name__ :List[str]=64 , __magic_name__ :Optional[int]=[3, 4, 6, 5] , __magic_name__ :int=[2, 4, 8, 16] , __magic_name__ :str=7 , __magic_name__ :Tuple=3.0 , __magic_name__ :Dict=True , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.1 , __magic_name__ :Optional[Any]="gelu" , __magic_name__ :Optional[Any]=0.02 , __magic_name__ :Tuple=1E-5 , __magic_name__ :Union[str, Any]=0.0 , __magic_name__ :int=None , __magic_name__ :Any=None , **__magic_name__ :Dict , ): '''simple docstring''' super().__init__(**__magic_name__ ) a = patch_size a = num_channels a = embed_dim a = depths a = len(__magic_name__ ) a = num_heads a = kernel_size a = mlp_ratio a = qkv_bias a = hidden_dropout_prob a = attention_probs_dropout_prob a = drop_path_rate a = hidden_act a = layer_norm_eps a = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model a = int(embed_dim * 2 ** (len(__magic_name__ ) - 1) ) a = layer_scale_init_value a = ["""stem"""] + [F'stage{idx}' for idx in range(1 , len(__magic_name__ ) + 1 )] a , a = get_aligned_output_features_output_indices( out_features=__magic_name__ , out_indices=__magic_name__ , stage_names=self.stage_names )
347
1
import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class __lowerCAmelCase : def __init__( self :Tuple , __magic_name__ :List[str] , __magic_name__ :int=None , __magic_name__ :str=None , __magic_name__ :Dict=None , __magic_name__ :Union[str, Any]="resnet50" , __magic_name__ :int=3 , __magic_name__ :str=32 , __magic_name__ :int=3 , __magic_name__ :List[Any]=True , __magic_name__ :str=True , ): '''simple docstring''' a = parent a = out_indices if out_indices is not None else [4] a = stage_names a = out_features a = backbone a = batch_size a = image_size a = num_channels a = use_pretrained_backbone a = is_training def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = self.get_config() return config, pixel_values def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[Any] , __magic_name__ :Union[str, Any] ): '''simple docstring''' a = TimmBackbone(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): a = model(__magic_name__ ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a = config_and_inputs a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch @require_timm class __lowerCAmelCase ( __magic_name__ , __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = (TimmBackbone,) if is_torch_available() else () UpperCamelCase__ = {'''feature-extraction''': TimmBackbone} if is_torch_available() else {} UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = TimmBackboneModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = """resnet18""" a = """microsoft/resnet-18""" a = AutoBackbone.from_pretrained(__magic_name__ , use_timm_backbone=__magic_name__ ) a = AutoBackbone.from_pretrained(__magic_name__ ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) a = AutoBackbone.from_pretrained(__magic_name__ , use_timm_backbone=__magic_name__ , out_indices=[1, 2, 3] ) a = AutoBackbone.from_pretrained(__magic_name__ , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip("""TimmBackbone doesn't support feed forward chunking""" ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' pass @unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute""" ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass @unittest.skip("""TimmBackbone initialization is managed on the timm side""" ) def lowerCamelCase__ ( self :int ): '''simple docstring''' pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' pass @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""" ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def lowerCamelCase__ ( self :int ): '''simple docstring''' pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def lowerCamelCase__ ( self :int ): '''simple docstring''' pass @unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration.""" ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass @unittest.skip("""TimmBackbone doesn't support output_attentions.""" ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass @unittest.skip("""Safetensors is not supported by timm.""" ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__magic_name__ ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() a = True a = self.has_attentions # no need to test all models as different heads yield the same functionality a = self.all_model_classes[0] a = model_class(__magic_name__ ) model.to(__magic_name__ ) a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = model(**__magic_name__ ) a = outputs[0][-1] # Encoder-/Decoder-only models a = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: a = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=__magic_name__ ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model(**__magic_name__ ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None a = copy.deepcopy(__magic_name__ ) a = None a = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model(**__magic_name__ ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights a = copy.deepcopy(__magic_name__ ) a = False a = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model(**__magic_name__ )
347
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer a = flax_key_tuple[:-1] + ("""weight""",) a = torch.permute(__lowerCamelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCamelCase ): # linear layer a = flax_key_tuple[:-1] + ("""weight""",) a = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: a = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: if "metadata" in layer: a = layer.split("""metadata""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: a = layer.split("""kvstore""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: a = layer.split("""/""" ) a = """/""".join(split_layer[:-1] ) a = (split_layer[-1],) if "kvstore/path" in layer: a = f'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: a = """file""" else: a = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __A ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: a = rename_keys(__lowerCamelCase ) a = {} for k, v in current_block.items(): a = v a = new_current_block torch.save(__lowerCamelCase , __lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = WEIGHTS_NAME ) -> List[str]: a = convert_file_size_to_int(__lowerCamelCase ) a = [] a = {} a = 0 a = 0 os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: a = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] a = flatten_dict(__lowerCamelCase , sep="""/""" ) a = {} for layer in checkpoint_info.keys(): a , a , a = get_key_and_tensorstore_dict( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if curr_real_layer_name in all_layers: a = content else: a = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() a = torch.tensor(__lowerCamelCase ) a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts a , a = rename_base_flax_keys(tuple(key.split("""/""" ) ) , __lowerCamelCase ) a = """/""".join(__lowerCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: a = os.path.join( __lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block a = {} a = 0 a = raw_weights.to(getattr(__lowerCamelCase , __lowerCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index a = {} a = {} for idx, shard in enumerate(__lowerCamelCase ): a = weights_name.replace( """.bin""" , f'-{idx+1:05d}-of-{len(__lowerCamelCase ):05d}.bin' ) # len(sharded_state_dicts):05d} a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{idx+1:05d}-of-???.bin' ) ) os.rename(__lowerCamelCase , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) a = shard for key in shard: a = shard_file # Add the metadata a = {"""total_size""": total_size} a = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(__lowerCamelCase , __lowerCamelCase ) , """w""" , encoding="""utf-8""" ) as f: a = json.dumps(__lowerCamelCase , indent=2 , sort_keys=__lowerCamelCase ) + """\n""" f.write(__lowerCamelCase ) return metadata, index if __name__ == "__main__": __UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __UpperCamelCase : Any = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __A ( ) -> Tuple: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer a = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) a = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) a = TaTokenizer.from_pretrained("""t5-small""" ) a = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" a = tokenizer(__lowerCamelCase , return_tensors="""pt""" ).input_ids a = model.generate(__lowerCamelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
347
1
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: __UpperCamelCase : Tuple = None __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) __UpperCamelCase : List[str] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} __UpperCamelCase : Dict = { "vocab_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", }, "tokenizer_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/tokenizer.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/tokenizer.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/tokenizer.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/tokenizer.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/tokenizer.json", }, } # TODO(PVP) - this should be removed in Transformers v5 __UpperCamelCase : str = { "t5-small": 512, "t5-base": 512, "t5-large": 512, "t5-3b": 512, "t5-11b": 512, } class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] UpperCamelCase__ = TaTokenizer UpperCamelCase__ = [] def __init__( self :int , __magic_name__ :List[str]=None , __magic_name__ :Any=None , __magic_name__ :Dict="</s>" , __magic_name__ :str="<unk>" , __magic_name__ :int="<pad>" , __magic_name__ :int=100 , __magic_name__ :List[str]=None , **__magic_name__ :Optional[int] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: a = [F'<extra_id_{i}>' for i in range(__magic_name__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens a = len(set(filter(lambda __magic_name__ : bool("""extra_id_""" in str(__magic_name__ ) ) , __magic_name__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) super().__init__( __magic_name__ , tokenizer_file=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , extra_ids=__magic_name__ , additional_special_tokens=__magic_name__ , **__magic_name__ , ) a = vocab_file a = False if not self.vocab_file else True a = extra_ids @staticmethod def lowerCamelCase__ ( __magic_name__ :Tuple , __magic_name__ :int , __magic_name__ :List[str] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: a = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , __magic_name__ , ) return max_model_length def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :str , __magic_name__ :Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__magic_name__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a = os.path.join( __magic_name__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ): copyfile(self.vocab_file , __magic_name__ ) logger.info(F'Copy vocab file to {out_vocab_file}' ) return (out_vocab_file,) def lowerCamelCase__ ( self :int , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: a = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def lowerCamelCase__ ( self :Tuple , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return list( set(filter(lambda __magic_name__ : bool(re.search(r"""<extra_id_\d+>""" , __magic_name__ ) ) is not None , self.additional_special_tokens ) ) ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(__magic_name__ ) for token in self.get_sentinel_tokens()]
347
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __UpperCamelCase : Union[str, Any] = (720, 1_280) # Height, Width __UpperCamelCase : Any = (0.4, 0.6) # if height or width lower than this scale, drop it. __UpperCamelCase : str = 1 / 100 __UpperCamelCase : Optional[int] = "" __UpperCamelCase : List[Any] = "" __UpperCamelCase : Union[str, Any] = "" __UpperCamelCase : Tuple = 250 def __A ( ) -> None: a , a = get_dataset(__lowerCamelCase , __lowerCamelCase ) for index in range(__lowerCamelCase ): a = random.sample(range(len(__lowerCamelCase ) ) , 4 ) a , a , a = update_image_and_anno( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , filter_scale=__lowerCamelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' a = random_chars(32 ) a = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] a = f'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(f'{file_root}.jpg' , __lowerCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) a = [] for anno in new_annos: a = anno[3] - anno[1] a = anno[4] - anno[2] a = anno[1] + width / 2 a = anno[2] + height / 2 a = f'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(__lowerCamelCase ) with open(f'{file_root}.txt' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> tuple[list, list]: a = [] a = [] for label_file in glob.glob(os.path.join(__lowerCamelCase , """*.txt""" ) ): a = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCamelCase ) as in_file: a = in_file.readlines() a = os.path.join(__lowerCamelCase , f'{label_name}.jpg' ) a = [] for obj_list in obj_lists: a = obj_list.rstrip("""\n""" ).split(""" """ ) a = float(obj[1] ) - float(obj[3] ) / 2 a = float(obj[2] ) - float(obj[4] ) / 2 a = float(obj[1] ) + float(obj[3] ) / 2 a = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__lowerCamelCase ) labels.append(__lowerCamelCase ) return img_paths, labels def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 0.0 , ) -> tuple[list, list, str]: a = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = int(scale_x * output_size[1] ) a = int(scale_y * output_size[0] ) a = [] a = [] for i, index in enumerate(__lowerCamelCase ): a = all_img_list[index] path_list.append(__lowerCamelCase ) a = all_annos[index] a = cva.imread(__lowerCamelCase ) if i == 0: # top-left a = cva.resize(__lowerCamelCase , (divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = bbox[2] * scale_y a = bbox[3] * scale_x a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right a = cva.resize(__lowerCamelCase , (output_size[1] - divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = bbox[2] * scale_y a = scale_x + bbox[3] * (1 - scale_x) a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left a = cva.resize(__lowerCamelCase , (divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = scale_y + bbox[2] * (1 - scale_y) a = bbox[3] * scale_x a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right a = cva.resize( __lowerCamelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = scale_y + bbox[2] * (1 - scale_y) a = scale_x + bbox[3] * (1 - scale_x) a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: a = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __A ( __lowerCamelCase ) -> str: assert number_char > 1, "The number of character should greater than 1" a = ascii_lowercase + digits return "".join(random.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
347
1
from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=__magic_name__ ): UpperCamelCase__ = ['''keras_nlp'''] def __init__( self :Union[str, Any] , *__magic_name__ :Union[str, Any] , **__magic_name__ :str ): '''simple docstring''' requires_backends(self , ["""keras_nlp"""] )
347
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Optional[Any] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "MobileNetV2OnnxConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ["MobileNetV2FeatureExtractor"] __UpperCamelCase : Tuple = ["MobileNetV2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV2ForImageClassification", "MobileNetV2ForSemanticSegmentation", "MobileNetV2Model", "MobileNetV2PreTrainedModel", "load_tf_weights_in_mobilenet_v2", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) __UpperCamelCase : Any = logging.getLogger(__name__) def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: a = np.argmax(__lowerCamelCase , axis=1 ) return np.sum(outputs == labels ) def __A ( __lowerCamelCase ) -> int: with open(__lowerCamelCase , encoding="""utf_8""" ) as f: a = csv.reader(__lowerCamelCase ) a = [] next(__lowerCamelCase ) # skip the first line for line in tqdm(__lowerCamelCase ): output.append((""" """.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: a = [] for dataset in encoded_datasets: a = len(__lowerCamelCase ) a = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) a = np.zeros((n_batch, 2) , dtype=np.intaa ) a = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) a = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(__lowerCamelCase ): a = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] a = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] a = with_conta a = with_conta a = len(__lowerCamelCase ) - 1 a = len(__lowerCamelCase ) - 1 a = with_conta a = with_conta a = mc_label a = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(__lowerCamelCase ) for t in all_inputs ) ) return tensor_datasets def __A ( ) -> Union[str, Any]: a = argparse.ArgumentParser() parser.add_argument("""--model_name""" , type=__lowerCamelCase , default="""openai-gpt""" , help="""pretrained model name""" ) parser.add_argument("""--do_train""" , action="""store_true""" , help="""Whether to run training.""" ) parser.add_argument("""--do_eval""" , action="""store_true""" , help="""Whether to run eval on the dev set.""" ) parser.add_argument( """--output_dir""" , default=__lowerCamelCase , type=__lowerCamelCase , required=__lowerCamelCase , help="""The output directory where the model predictions and checkpoints will be written.""" , ) parser.add_argument("""--train_dataset""" , type=__lowerCamelCase , default="""""" ) parser.add_argument("""--eval_dataset""" , type=__lowerCamelCase , default="""""" ) parser.add_argument("""--seed""" , type=__lowerCamelCase , default=42 ) parser.add_argument("""--num_train_epochs""" , type=__lowerCamelCase , default=3 ) parser.add_argument("""--train_batch_size""" , type=__lowerCamelCase , default=8 ) parser.add_argument("""--eval_batch_size""" , type=__lowerCamelCase , default=16 ) parser.add_argument("""--adam_epsilon""" , default=1E-8 , type=__lowerCamelCase , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , type=__lowerCamelCase , default=1 ) parser.add_argument( """--max_steps""" , default=-1 , type=__lowerCamelCase , help=( """If > 0: set total number of training steps to perform. Override num_train_epochs.""" ) , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCamelCase , default=1 , help="""Number of updates steps to accumulate before performing a backward/update pass.""" , ) parser.add_argument("""--learning_rate""" , type=__lowerCamelCase , default=6.2_5E-5 ) parser.add_argument("""--warmup_steps""" , default=0 , type=__lowerCamelCase , help="""Linear warmup over warmup_steps.""" ) parser.add_argument("""--lr_schedule""" , type=__lowerCamelCase , default="""warmup_linear""" ) parser.add_argument("""--weight_decay""" , type=__lowerCamelCase , default=0.01 ) parser.add_argument("""--lm_coef""" , type=__lowerCamelCase , default=0.9 ) parser.add_argument("""--n_valid""" , type=__lowerCamelCase , default=374 ) parser.add_argument("""--server_ip""" , type=__lowerCamelCase , default="""""" , help="""Can be used for distant debugging.""" ) parser.add_argument("""--server_port""" , type=__lowerCamelCase , default="""""" , help="""Can be used for distant debugging.""" ) a = parser.parse_args() print(__lowerCamelCase ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("""Waiting for debugger attach""" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=__lowerCamelCase ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) a = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) a = torch.cuda.device_count() logger.info("""device: {}, n_gpu {}""".format(__lowerCamelCase , __lowerCamelCase ) ) if not args.do_train and not args.do_eval: raise ValueError("""At least one of `do_train` or `do_eval` must be True.""" ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset a = ["""_start_""", """_delimiter_""", """_classify_"""] a = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(__lowerCamelCase ) a = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) a = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(__lowerCamelCase ) ) model.to(__lowerCamelCase ) # Load and encode the datasets def tokenize_and_encode(__lowerCamelCase ): if isinstance(__lowerCamelCase , __lowerCamelCase ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(__lowerCamelCase ) ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): return obj return [tokenize_and_encode(__lowerCamelCase ) for o in obj] logger.info("""Encoding dataset...""" ) a = load_rocstories_dataset(args.train_dataset ) a = load_rocstories_dataset(args.eval_dataset ) a = (train_dataset, eval_dataset) a = tokenize_and_encode(__lowerCamelCase ) # Compute the max input length for the Transformer a = model.config.n_positions // 2 - 2 a = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) a = min(__lowerCamelCase , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders a = pre_process_datasets(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , *__lowerCamelCase ) a , a = tensor_datasets[0], tensor_datasets[1] a = TensorDataset(*__lowerCamelCase ) a = RandomSampler(__lowerCamelCase ) a = DataLoader(__lowerCamelCase , sampler=__lowerCamelCase , batch_size=args.train_batch_size ) a = TensorDataset(*__lowerCamelCase ) a = SequentialSampler(__lowerCamelCase ) a = DataLoader(__lowerCamelCase , sampler=__lowerCamelCase , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: a = args.max_steps a = args.max_steps // (len(__lowerCamelCase ) // args.gradient_accumulation_steps) + 1 else: a = len(__lowerCamelCase ) // args.gradient_accumulation_steps * args.num_train_epochs a = list(model.named_parameters() ) a = ["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""] a = [ { """params""": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], """weight_decay""": args.weight_decay, }, {"""params""": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], """weight_decay""": 0.0}, ] a = AdamW(__lowerCamelCase , lr=args.learning_rate , eps=args.adam_epsilon ) a = get_linear_schedule_with_warmup( __lowerCamelCase , num_warmup_steps=args.warmup_steps , num_training_steps=__lowerCamelCase ) if args.do_train: a , a , a = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="""Epoch""" ): a = 0 a = 0 a = tqdm(__lowerCamelCase , desc="""Training""" ) for step, batch in enumerate(__lowerCamelCase ): a = tuple(t.to(__lowerCamelCase ) for t in batch ) a , a , a , a = batch a = model(__lowerCamelCase , mc_token_ids=__lowerCamelCase , lm_labels=__lowerCamelCase , mc_labels=__lowerCamelCase ) a = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() a = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 a = """Training loss: {:.2e} lr: {:.2e}""".format(__lowerCamelCase , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer a = model.module if hasattr(__lowerCamelCase , """module""" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` a = os.path.join(args.output_dir , __lowerCamelCase ) a = os.path.join(args.output_dir , __lowerCamelCase ) torch.save(model_to_save.state_dict() , __lowerCamelCase ) model_to_save.config.to_json_file(__lowerCamelCase ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned a = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) a = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(__lowerCamelCase ) if args.do_eval: model.eval() a , a = 0, 0 a , a = 0, 0 for batch in tqdm(__lowerCamelCase , desc="""Evaluating""" ): a = tuple(t.to(__lowerCamelCase ) for t in batch ) a , a , a , a = batch with torch.no_grad(): a , a , a , a = model( __lowerCamelCase , mc_token_ids=__lowerCamelCase , lm_labels=__lowerCamelCase , mc_labels=__lowerCamelCase ) a = mc_logits.detach().cpu().numpy() a = mc_labels.to("""cpu""" ).numpy() a = accuracy(__lowerCamelCase , __lowerCamelCase ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 a = eval_loss / nb_eval_steps a = eval_accuracy / nb_eval_examples a = tr_loss / nb_tr_steps if args.do_train else None a = {"""eval_loss""": eval_loss, """eval_accuracy""": eval_accuracy, """train_loss""": train_loss} a = os.path.join(args.output_dir , """eval_results.txt""" ) with open(__lowerCamelCase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , __lowerCamelCase , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) if __name__ == "__main__": main()
347
def __A ( __lowerCamelCase ) -> bool: if num < 0: return False a = num a = 0 while num > 0: a = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
1
import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def __A ( __lowerCamelCase ) -> Optional[Any]: return EnvironmentCommand() class __lowerCAmelCase ( __magic_name__ ): @staticmethod def lowerCamelCase__ ( __magic_name__ :ArgumentParser ): '''simple docstring''' a = parser.add_parser("""env""" ) download_parser.set_defaults(func=__magic_name__ ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = huggingface_hub.__version__ a = """not installed""" a = """NA""" if is_torch_available(): import torch a = torch.__version__ a = torch.cuda.is_available() a = """not installed""" if is_transformers_available(): import transformers a = transformers.__version__ a = """not installed""" if is_accelerate_available(): import accelerate a = accelerate.__version__ a = """not installed""" if is_xformers_available(): import xformers a = xformers.__version__ a = { """`diffusers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """PyTorch version (GPU?)""": F'{pt_version} ({pt_cuda_available})', """Huggingface_hub version""": hub_version, """Transformers version""": transformers_version, """Accelerate version""": accelerate_version, """xFormers version""": xformers_version, """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(__magic_name__ ) ) return info @staticmethod def lowerCamelCase__ ( __magic_name__ :Union[str, Any] ): '''simple docstring''' return "\n".join([F'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
347
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = CanineTokenizer UpperCamelCase__ = False def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().setUp() a = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return CanineTokenizer.from_pretrained("""google/canine-s""" ) def lowerCamelCase__ ( self :Tuple , **__magic_name__ :Dict ): '''simple docstring''' a = self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) a = 1024 return tokenizer @require_torch def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.canine_tokenizer a = ["""Life is like a box of chocolates.""", """You never know what you're gonna get."""] # fmt: off a = [5_7344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 5_7345, 0, 0, 0, 0] # fmt: on a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) self.assertIsInstance(__magic_name__ , __magic_name__ ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = ["""Once there was a man.""", """He wrote a test in HuggingFace Tranformers."""] a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("""input_ids""" , __magic_name__ ) self.assertIn("""attention_mask""" , __magic_name__ ) self.assertIn("""token_type_ids""" , __magic_name__ ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = [ """What's the weater?""", """It's about 25 degrees.""", ] a = tokenizer( text_target=__magic_name__ , max_length=32 , padding="""max_length""" , truncation=__magic_name__ , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) shutil.rmtree(__magic_name__ ) a = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: a = chr(0Xe_0_0_7 ) additional_special_tokens.append(__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertIn(__magic_name__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) a = tokenizer.__class__.from_pretrained(__magic_name__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a , a = self.get_clean_sequence(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_5 a = chr(__magic_name__ ) tokenizer.add_special_tokens({"""cls_token""": special_token} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) a = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , input_encoded + special_token_id ) a = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertTrue(special_token not in decoded ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = chr(0Xe_0_0_5 ) a = chr(0Xe_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=__magic_name__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"""additional_special_tokens""": [SPECIAL_TOKEN_2]} ) a = tokenizer.tokenize(__magic_name__ ) a = tokenizer.tokenize(__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(token_a[0] , __magic_name__ ) self.assertEqual(token_a[0] , __magic_name__ ) @require_tokenizers def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(__magic_name__ ) tokenizer.from_pretrained(__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__magic_name__ ) with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = [new_token_a] a = [new_token_a] with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files a = tokenizer_class.from_pretrained(__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) a = 0Xe_0_0_7 a = chr(__magic_name__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained a = [AddedToken(__magic_name__ , lstrip=__magic_name__ )] a = tokenizer_class.from_pretrained( __magic_name__ , additional_special_tokens=__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = """hello world""" if self.space_between_special_tokens: a = """[CLS] hello world [SEP]""" else: a = input a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.decode(__magic_name__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(__magic_name__ , [output, output.lower()] ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = [ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] a = """a""" a = ord(__magic_name__ ) for attr in attributes_list: setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [] ) a = 0Xe_0_0_6 a = chr(__magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [additional_special_token_id] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [additional_special_token] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [additional_special_token_id] ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :str ): '''simple docstring''' pass def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass
347
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = AutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" , return_dict=__magic_name__ ).to(__magic_name__ ) a = AutoTokenizer.from_pretrained("""google/mt5-small""" ) a = tokenizer("""Hello there""" , return_tensors="""pt""" ).input_ids a = tokenizer("""Hi I am""" , return_tensors="""pt""" ).input_ids a = model(input_ids.to(__magic_name__ ) , labels=labels.to(__magic_name__ ) ).loss a = -(labels.shape[-1] * loss.item()) a = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
347
def __A ( __lowerCamelCase ) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
347
1
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class __lowerCAmelCase ( __magic_name__ ): def __init__( self :Tuple , __magic_name__ :Any , __magic_name__ :Optional[int] ): '''simple docstring''' a = params a = np.array(__magic_name__ ) a = np.array([len(__magic_name__ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self :List[Any] , __magic_name__ :str ): '''simple docstring''' return (self.token_ids[index], self.lengths[index]) def __len__( self :int ): '''simple docstring''' return len(self.lengths ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.params.max_model_input_size a = self.lengths > max_len logger.info(F'Splitting {sum(__magic_name__ )} too long sequences.' ) def divide_chunks(__magic_name__ :List[Any] , __magic_name__ :str ): return [l[i : i + n] for i in range(0 , len(__magic_name__ ) , __magic_name__ )] a = [] a = [] if self.params.mlm: a , a = self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""] else: a , a = self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: a = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: a = np.insert(__magic_name__ , 0 , __magic_name__ ) if sub_s[-1] != sep_id: a = np.insert(__magic_name__ , len(__magic_name__ ) , __magic_name__ ) assert len(__magic_name__ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(__magic_name__ ) new_tok_ids.extend(__magic_name__ ) new_lengths.extend([len(__magic_name__ ) for l in sub_seqs] ) a = np.array(__magic_name__ ) a = np.array(__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = len(self ) a = self.lengths > 11 a = self.token_ids[indices] a = self.lengths[indices] a = len(self ) logger.info(F'Remove {init_size - new_size} too short (<=11 tokens) sequences.' ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' if "unk_token" not in self.params.special_tok_ids: return else: a = self.params.special_tok_ids["""unk_token"""] a = len(self ) a = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) a = (unk_occs / self.lengths) < 0.5 a = self.token_ids[indices] a = self.lengths[indices] a = len(self ) logger.info(F'Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).' ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' if not self.params.is_master: return logger.info(F'{len(self )} sequences' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def lowerCamelCase__ ( self :Any , __magic_name__ :Optional[int] ): '''simple docstring''' a = [t[0] for t in batch] a = [t[1] for t in batch] assert len(__magic_name__ ) == len(__magic_name__ ) # Max for paddings a = max(__magic_name__ ) # Pad token ids if self.params.mlm: a = self.params.special_tok_ids["""pad_token"""] else: a = self.params.special_tok_ids["""unk_token"""] a = [list(t.astype(__magic_name__ ) ) + [pad_idx] * (max_seq_len_ - len(__magic_name__ )) for t in token_ids] assert len(tk_ ) == len(__magic_name__ ) assert all(len(__magic_name__ ) == max_seq_len_ for t in tk_ ) a = torch.tensor(tk_ ) # (bs, max_seq_len_) a = torch.tensor(__magic_name__ ) # (bs) return tk_t, lg_t
347
def __A ( __lowerCamelCase ) -> int: if not numbers: return 0 if not isinstance(__lowerCamelCase , (list, tuple) ) or not all( isinstance(__lowerCamelCase , __lowerCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) a = a = a = numbers[0] for i in range(1 , len(__lowerCamelCase ) ): # update the maximum and minimum subarray products a = numbers[i] if number < 0: a , a = min_till_now, max_till_now a = max(__lowerCamelCase , max_till_now * number ) a = min(__lowerCamelCase , min_till_now * number ) # update the maximum product found till now a = max(__lowerCamelCase , __lowerCamelCase ) return max_prod
347
1
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCamelCase : Optional[Any] = { "configuration_wav2vec2": ["WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2Config"], "feature_extraction_wav2vec2": ["Wav2Vec2FeatureExtractor"], "processing_wav2vec2": ["Wav2Vec2Processor"], "tokenization_wav2vec2": ["Wav2Vec2CTCTokenizer", "Wav2Vec2Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = [ "WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ForAudioFrameClassification", "Wav2Vec2ForCTC", "Wav2Vec2ForMaskedLM", "Wav2Vec2ForPreTraining", "Wav2Vec2ForSequenceClassification", "Wav2Vec2ForXVector", "Wav2Vec2Model", "Wav2Vec2PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ "TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWav2Vec2ForCTC", "TFWav2Vec2Model", "TFWav2Vec2PreTrainedModel", "TFWav2Vec2ForSequenceClassification", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "FlaxWav2Vec2ForCTC", "FlaxWav2Vec2ForPreTraining", "FlaxWav2Vec2Model", "FlaxWav2Vec2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class __lowerCAmelCase : def __init__( self :List[Any] , __magic_name__ :Tuple , __magic_name__ :List[str]=14 , __magic_name__ :List[Any]=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :str=True , __magic_name__ :List[str]=False , __magic_name__ :Any=True , __magic_name__ :Optional[int]=99 , __magic_name__ :Dict=32 , __magic_name__ :int=4 , __magic_name__ :int=4 , __magic_name__ :str=4 , __magic_name__ :Any=37 , __magic_name__ :List[Any]="gelu" , __magic_name__ :Any=0.1 , __magic_name__ :Optional[int]=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Any=0.02 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = rotary_dim a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = initializer_range a = None a = vocab_size - 1 a = vocab_size - 1 a = vocab_size - 1 def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=__magic_name__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCamelCase__ ( self :int , __magic_name__ :int , __magic_name__ :str , __magic_name__ :str , __magic_name__ :Dict ): '''simple docstring''' a = 20 a = model_class_name(__magic_name__ ) a = model.init_cache(input_ids.shape[0] , __magic_name__ ) a = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) a = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) a = model( input_ids[:, :-1] , attention_mask=__magic_name__ , past_key_values=__magic_name__ , position_ids=__magic_name__ , ) a = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) a = model( input_ids[:, -1:] , attention_mask=__magic_name__ , past_key_values=outputs_cache.past_key_values , position_ids=__magic_name__ , ) a = model(__magic_name__ ) a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F'Max diff is {diff}' ) def lowerCamelCase__ ( self :Any , __magic_name__ :Tuple , __magic_name__ :List[str] , __magic_name__ :int , __magic_name__ :Any ): '''simple docstring''' a = 20 a = model_class_name(__magic_name__ ) a = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) a = model.init_cache(input_ids.shape[0] , __magic_name__ ) a = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) a = model( input_ids[:, :-1] , attention_mask=__magic_name__ , past_key_values=__magic_name__ , position_ids=__magic_name__ , ) a = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) a = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=__magic_name__ , position_ids=__magic_name__ , ) a = model(__magic_name__ , attention_mask=__magic_name__ ) a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F'Max diff is {diff}' ) @require_flax class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () UpperCamelCase__ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowerCamelCase__ ( self :str ): '''simple docstring''' a = FlaxGPTJModelTester(self ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' for model_class_name in self.all_model_classes: a , a , a = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' for model_class_name in self.all_model_classes: a , a , a = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) @tooslow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = GPTaTokenizer.from_pretrained("""gpt2""" , pad_token="""<|endoftext|>""" , padding_side="""left""" ) a = tokenizer(["""Hello this is a long string""", """Hey"""] , return_tensors="""np""" , padding=__magic_name__ , truncation=__magic_name__ ) a = FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B""" ) a = False a = model.config.eos_token_id a = jax.jit(model.generate ) a = jit_generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , pad_token_id=tokenizer.pad_token_id ).sequences a = tokenizer.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ ) a = [ """Hello this is a long string of text.\n\nI'm trying to get the text of the""", """Hey, I'm a little late to the party. I'm going to""", ] self.assertListEqual(__magic_name__ , __magic_name__ ) @is_pt_flax_cross_test def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class a = model_class.__name__[4:] # Skip the "Flax" at the beginning a = getattr(__magic_name__ , __magic_name__ ) a , a = pt_inputs["""input_ids"""].shape a = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__magic_name__ ): a = 0 a = 1 a = 0 a = 1 a = pt_model_class(__magic_name__ ).eval() a = model_class(__magic_name__ , dtype=jnp.floataa ) a = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , __magic_name__ ) a = fx_state with torch.no_grad(): a = pt_model(**__magic_name__ ).to_tuple() a = fx_model(**__magic_name__ ).to_tuple() self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(__magic_name__ , __magic_name__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(__magic_name__ ) a = model_class.from_pretrained(__magic_name__ , from_pt=__magic_name__ ) a = fx_model_loaded(**__magic_name__ ).to_tuple() self.assertEqual( len(__magic_name__ ) , len(__magic_name__ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(__magic_name__ , __magic_name__ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs a = self._prepare_for_class(__magic_name__ , __magic_name__ ) a = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class a = model_class.__name__[4:] # Skip the "Flax" at the beginning a = getattr(__magic_name__ , __magic_name__ ) a = pt_model_class(__magic_name__ ).eval() a = model_class(__magic_name__ , dtype=jnp.floataa ) a = load_flax_weights_in_pytorch_model(__magic_name__ , fx_model.params ) a , a = pt_inputs["""input_ids"""].shape a = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__magic_name__ ): a = 0 a = 1 a = 0 a = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): a = pt_model(**__magic_name__ ).to_tuple() a = fx_model(**__magic_name__ ).to_tuple() self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(__magic_name__ , __magic_name__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(__magic_name__ ) a = pt_model_class.from_pretrained(__magic_name__ , from_flax=__magic_name__ ) with torch.no_grad(): a = pt_model_loaded(**__magic_name__ ).to_tuple() self.assertEqual( len(__magic_name__ ) , len(__magic_name__ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(__magic_name__ , __magic_name__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""EleutherAI/gpt-j-6B""" ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ )
347
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCamelCase ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(__lowerCamelCase ) assert result == expected
347
1
import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = DebertaTokenizer UpperCamelCase__ = True UpperCamelCase__ = DebertaTokenizerFast def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt a = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """[UNK]""", ] a = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) a = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] a = {"""unk_token""": """[UNK]"""} a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__magic_name__ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__magic_name__ ) ) def lowerCamelCase__ ( self :str , **__magic_name__ :Any ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) def lowerCamelCase__ ( self :str , __magic_name__ :int ): '''simple docstring''' a = """lower newer""" a = """lower newer""" return input_text, output_text def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.get_tokenizer() a = """lower newer""" a = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] a = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) a = tokens + [tokenizer.unk_token] a = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizer() a = tokenizer("""Hello""" , """World""" ) a = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd["""token_type_ids"""] , __magic_name__ ) @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.tokenizer_class.from_pretrained("""microsoft/deberta-base""" ) a = tokenizer.encode("""sequence builders""" , add_special_tokens=__magic_name__ ) a = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__magic_name__ ) a = tokenizer.encode( """sequence builders""" , add_special_tokens=__magic_name__ , add_prefix_space=__magic_name__ ) a = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=__magic_name__ , add_prefix_space=__magic_name__ ) a = tokenizer.build_inputs_with_special_tokens(__magic_name__ ) a = tokenizer.build_inputs_with_special_tokens(__magic_name__ , __magic_name__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: a = tokenizer_class.from_pretrained("""microsoft/deberta-base""" ) a = [ """ALBERT: A Lite BERT for Self-supervised Learning of Language Representations""", """ALBERT incorporates two parameter reduction techniques""", """The first one is a factorized embedding parameterization. By decomposing the large vocabulary""" """ embedding matrix into two small matrices, we separate the size of the hidden layers from the size of""" """ vocabulary embedding.""", ] a = tokenizer(__magic_name__ , padding=__magic_name__ ) a = [tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) for seq in encoding["""input_ids"""]] # fmt: off a = { """input_ids""": [ [1, 2118, 1_1126, 565, 35, 83, 2_5191, 163, 1_8854, 13, 1_2156, 12, 1_6101, 2_5376, 1_3807, 9, 2_2205, 2_7893, 1635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2118, 1_1126, 565, 2_4536, 80, 4_3797, 4878, 7373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 133, 78, 65, 16, 10, 3724, 1538, 3_3183, 1_1303, 4_3797, 1938, 4, 870, 2_4165, 2_9105, 5, 739, 3_2644, 3_3183, 1_1303, 3_6173, 88, 80, 650, 7821, 4_5940, 6, 52, 2559, 5, 1836, 9, 5, 7397, 1_3171, 31, 5, 1836, 9, 3_2644, 3_3183, 1_1303, 4, 2] ], """token_type_ids""": [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on a = [ """ALBERT: A Lite BERT for Self-supervised Learning of Language Representations""", """ALBERT incorporates two parameter reduction techniques""", """The first one is a factorized embedding parameterization. By decomposing the large vocabulary""" """ embedding matrix into two small matrices, we separate the size of the hidden layers from the size of""" """ vocabulary embedding.""", ] self.assertDictEqual(encoding.data , __magic_name__ ) for expected, decoded in zip(__magic_name__ , __magic_name__ ): self.assertEqual(__magic_name__ , __magic_name__ )
347
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __A ( __lowerCamelCase ) -> bool: a = int(number**0.5 ) return number == sq * sq def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> tuple[int, int]: a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den a = x_den * y_den * z_den a = gcd(__lowerCamelCase , __lowerCamelCase ) top //= hcf bottom //= hcf return top, bottom def __A ( __lowerCamelCase = 35 ) -> int: a = set() a = 42 a = Fraction(0 ) a = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 a = x_num * y_den + x_den * y_num a = x_den * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) a = x_den * x_den * y_den * y_den if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=-1 a = x_num * y_num a = x_den * y_num + x_num * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = x_num * x_num * y_num * y_num a = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) for num, den in unique_s: total += Fraction(__lowerCamelCase , __lowerCamelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(F'{solution() = }')
347
1
import sys from collections import defaultdict class __lowerCAmelCase : def __init__( self :List[str] ): '''simple docstring''' a = [] def lowerCamelCase__ ( self :List[Any] , __magic_name__ :int ): '''simple docstring''' return self.node_position[vertex] def lowerCamelCase__ ( self :Any , __magic_name__ :Dict , __magic_name__ :Union[str, Any] ): '''simple docstring''' a = pos def lowerCamelCase__ ( self :Dict , __magic_name__ :Optional[int] , __magic_name__ :Union[str, Any] , __magic_name__ :List[Any] , __magic_name__ :Any ): '''simple docstring''' if start > size // 2 - 1: return else: if 2 * start + 2 >= size: a = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: a = 2 * start + 1 else: a = 2 * start + 2 if heap[smallest_child] < heap[start]: a , a = heap[smallest_child], positions[smallest_child] a , a = ( heap[start], positions[start], ) a , a = temp, tempa a = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __magic_name__ ) self.top_to_bottom(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :str , __magic_name__ :Tuple , __magic_name__ :Optional[Any] , __magic_name__ :List[str] , __magic_name__ :List[Any] ): '''simple docstring''' a = position[index] while index != 0: a = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: a = heap[parent] a = position[parent] self.set_position(position[parent] , __magic_name__ ) else: a = val a = temp self.set_position(__magic_name__ , __magic_name__ ) break a = parent else: a = val a = temp self.set_position(__magic_name__ , 0 ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Optional[Any] , __magic_name__ :str ): '''simple docstring''' a = len(__magic_name__ ) // 2 - 1 for i in range(__magic_name__ , -1 , -1 ): self.top_to_bottom(__magic_name__ , __magic_name__ , len(__magic_name__ ) , __magic_name__ ) def lowerCamelCase__ ( self :int , __magic_name__ :Optional[int] , __magic_name__ :Optional[int] ): '''simple docstring''' a = positions[0] a = sys.maxsize self.top_to_bottom(__magic_name__ , 0 , len(__magic_name__ ) , __magic_name__ ) return temp def __A ( __lowerCamelCase ) -> Tuple: a = Heap() a = [0] * len(__lowerCamelCase ) a = [-1] * len(__lowerCamelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph a = [] # Heap of Distance of vertices from their neighboring vertex a = [] for vertex in range(len(__lowerCamelCase ) ): distance_tv.append(sys.maxsize ) positions.append(__lowerCamelCase ) heap.node_position.append(__lowerCamelCase ) a = [] a = 1 a = sys.maxsize for neighbor, distance in adjacency_list[0]: a = 0 a = distance heap.heapify(__lowerCamelCase , __lowerCamelCase ) for _ in range(1 , len(__lowerCamelCase ) ): a = heap.delete_minimum(__lowerCamelCase , __lowerCamelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) a = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(__lowerCamelCase )] ): a = distance heap.bottom_to_top( __lowerCamelCase , heap.get_position(__lowerCamelCase ) , __lowerCamelCase , __lowerCamelCase ) a = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > __UpperCamelCase : Optional[int] = int(input("Enter number of edges: ").strip()) __UpperCamelCase : Union[str, Any] = defaultdict(list) for _ in range(edges_number): __UpperCamelCase : int = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
347
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :List[str] , __magic_name__ :List[str] , __magic_name__ :List[Any]=13 , __magic_name__ :Any=7 , __magic_name__ :Optional[int]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :Any=99 , __magic_name__ :List[str]=32 , __magic_name__ :List[str]=5 , __magic_name__ :str=4 , __magic_name__ :str=37 , __magic_name__ :Optional[int]="gelu" , __magic_name__ :int=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Tuple=16 , __magic_name__ :Tuple=2 , __magic_name__ :List[str]=0.02 , __magic_name__ :Any=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = FlaxRoFormerModelTester(self ) @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) a = jnp.array([[0, 1, 2, 3, 4, 5]] ) a = model(__magic_name__ )[0] a = 5_0000 a = (1, 6, vocab_size) self.assertEqual(output.shape , __magic_name__ ) a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
from __future__ import annotations from collections.abc import Callable __UpperCamelCase : List[Any] = list[list[float | int]] def __A ( __lowerCamelCase , __lowerCamelCase ) -> Matrix: a = len(__lowerCamelCase ) a = [[0 for _ in range(size + 1 )] for _ in range(__lowerCamelCase )] a = 42 a = 42 a = 42 a = 42 a = 42 a = 42 for row in range(__lowerCamelCase ): for col in range(__lowerCamelCase ): a = matrix[row][col] a = vector[row][0] a = 0 a = 0 while row < size and col < size: # pivoting a = max((abs(augmented[rowa][col] ), rowa) for rowa in range(__lowerCamelCase , __lowerCamelCase ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: a , a = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , __lowerCamelCase ): a = augmented[rowa][col] / augmented[row][col] a = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , __lowerCamelCase ): for row in range(__lowerCamelCase ): a = augmented[row][col] / augmented[col][col] for cola in range(__lowerCamelCase , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(__lowerCamelCase ) ] def __A ( __lowerCamelCase ) -> Callable[[int], int]: a = len(__lowerCamelCase ) a = [[0 for _ in range(__lowerCamelCase )] for _ in range(__lowerCamelCase )] a = [[0] for _ in range(__lowerCamelCase )] a = 42 a = 42 a = 42 a = 42 for x_val, y_val in enumerate(__lowerCamelCase ): for col in range(__lowerCamelCase ): a = (x_val + 1) ** (size - col - 1) a = y_val a = solve(__lowerCamelCase , __lowerCamelCase ) def interpolated_func(__lowerCamelCase ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(__lowerCamelCase ) ) return interpolated_func def __A ( __lowerCamelCase ) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def __A ( __lowerCamelCase = question_function , __lowerCamelCase = 10 ) -> int: a = [func(__lowerCamelCase ) for x_val in range(1 , order + 1 )] a = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] a = 0 a = 42 a = 42 for poly in polynomials: a = 1 while func(__lowerCamelCase ) == poly(__lowerCamelCase ): x_val += 1 ret += poly(__lowerCamelCase ) return ret if __name__ == "__main__": print(F'{solution() = }')
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
def __A ( __lowerCamelCase ) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
347
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = (IPNDMScheduler,) UpperCamelCase__ = (('''num_inference_steps''', 50),) def lowerCamelCase__ ( self :Any , **__magic_name__ :Optional[Any] ): '''simple docstring''' a = {"""num_train_timesteps""": 1000} config.update(**__magic_name__ ) return config def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple=0 , **__magic_name__ :Optional[int] ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] , __magic_name__ :List[Any]=0 , **__magic_name__ :Any ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residuals (must be after setting timesteps) a = dummy_past_residuals[:] if time_step is None: a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__magic_name__ ) a = scheduler_class.from_pretrained(__magic_name__ ) # copy over dummy past residuals new_scheduler.set_timesteps(__magic_name__ ) # copy over dummy past residual (must be after setting timesteps) a = dummy_past_residuals[:] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = new_scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self :Optional[Any] , **__magic_name__ :Optional[int] ): '''simple docstring''' a = self.scheduler_classes[0] a = self.get_scheduler_config(**__magic_name__ ) a = scheduler_class(**__magic_name__ ) a = 10 a = self.dummy_model() a = self.dummy_sample_deter scheduler.set_timesteps(__magic_name__ ) for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample for i, t in enumerate(scheduler.timesteps ): a = model(__magic_name__ , __magic_name__ ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample return sample def lowerCamelCase__ ( self :str ): '''simple docstring''' a = dict(self.forward_default_kwargs ) a = kwargs.pop("""num_inference_steps""" , __magic_name__ ) for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__magic_name__ ) a = self.dummy_sample a = 0.1 * sample if num_inference_steps is not None and hasattr(__magic_name__ , """set_timesteps""" ): scheduler.set_timesteps(__magic_name__ ) elif num_inference_steps is not None and not hasattr(__magic_name__ , """set_timesteps""" ): a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] a = dummy_past_residuals[:] a = scheduler.timesteps[5] a = scheduler.timesteps[6] a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample a = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__magic_name__ , time_step=__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.full_loop() a = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_mean.item() - 254_0529 ) < 10
347
1
import argparse from collections import defaultdict def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: a = f'{file}_{class_name}_{test_name}' done_test[_id] += 1 with open(__lowerCamelCase , """r""" ) as f: a = f.readlines() a = f'class {class_name}(' a = f'{4 * " "}def {test_name}(' a = f'{8 * " "}{correct_line.split()[0]}' a = f'{16 * " "}{correct_line.split()[0]}' a = False a = False a = False a = False a = 0 a = 0 a = [] for line in lines: if line.startswith(__lowerCamelCase ): a = True elif in_class and line.startswith(__lowerCamelCase ): a = True elif in_class and in_func and (line.startswith(__lowerCamelCase ) or line.startswith(__lowerCamelCase )): a = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: a = True if in_class and in_func and in_line: if ")" not in line: continue else: a = True if in_class and in_func and in_line and insert_line: new_lines.append(f'{spaces * " "}{correct_line}' ) a = a = a = a = False else: new_lines.append(__lowerCamelCase ) with open(__lowerCamelCase , """w""" ) as f: for line in new_lines: f.write(__lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase=None ) -> List[Any]: if fail is not None: with open(__lowerCamelCase , """r""" ) as f: a = {l.strip() for l in f.readlines()} else: a = None with open(__lowerCamelCase , """r""" ) as f: a = f.readlines() a = defaultdict(__lowerCamelCase ) for line in correct_lines: a , a , a , a = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": __UpperCamelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--correct_filename", help="filename of tests with expected result") parser.add_argument("--fail_filename", help="filename of test failures", type=str, default=None) __UpperCamelCase : Optional[Any] = parser.parse_args() main(args.correct_filename, args.fail_filename)
347
__UpperCamelCase : Dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __A ( ) -> None: a = input("""Enter message: """ ) a = input("""Enter key [alphanumeric]: """ ) a = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): a = """encrypt""" a = encrypt_message(__lowerCamelCase , __lowerCamelCase ) elif mode.lower().startswith("""d""" ): a = """decrypt""" a = decrypt_message(__lowerCamelCase , __lowerCamelCase ) print(f'\n{mode.title()}ed message:' ) print(__lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """encrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> str: return translate_message(__lowerCamelCase , __lowerCamelCase , """decrypt""" ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: a = [] a = 0 a = key.upper() for symbol in message: a = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__lowerCamelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__lowerCamelCase ): a = 0 else: translated.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) if __name__ == "__main__": main()
347
1
import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : Tuple = {"vocab_file": "spiece.model"} __UpperCamelCase : Optional[int] = { "vocab_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", } } # TODO(PVP) - this should be removed in Transformers v5 __UpperCamelCase : Optional[int] = { "t5-small": 512, "t5-base": 512, "t5-large": 512, "t5-3b": 512, "t5-11b": 512, } __UpperCamelCase : Tuple = "▁" class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :Optional[Any] , __magic_name__ :str , __magic_name__ :Tuple="</s>" , __magic_name__ :Any="<unk>" , __magic_name__ :Dict="<pad>" , __magic_name__ :Optional[Any]=100 , __magic_name__ :str=None , __magic_name__ :Optional[Dict[str, Any]] = None , __magic_name__ :Optional[Any]=True , **__magic_name__ :Optional[int] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: a = [F'<extra_id_{i}>' for i in range(__magic_name__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens a = len(set(filter(lambda __magic_name__ : bool("""extra_id""" in str(__magic_name__ ) ) , __magic_name__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" ) a = legacy a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , extra_ids=__magic_name__ , additional_special_tokens=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , legacy=__magic_name__ , **__magic_name__ , ) a = vocab_file a = extra_ids a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__magic_name__ ) @staticmethod def lowerCamelCase__ ( __magic_name__ :Dict , __magic_name__ :List[Any] , __magic_name__ :Any ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: a = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , __magic_name__ , ) return max_model_length @property def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' return self.sp_model.get_piece_size() + self._extra_ids def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None , __magic_name__ :bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__magic_name__ )) + [1] return ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def lowerCamelCase__ ( self :str ): '''simple docstring''' return list( set(filter(lambda __magic_name__ : bool(re.search(r"""<extra_id_\d+>""" , __magic_name__ ) ) is not None , self.additional_special_tokens ) ) ) def lowerCamelCase__ ( self :int ): '''simple docstring''' return [self._convert_token_to_id(__magic_name__ ) for token in self.get_sentinel_tokens()] def lowerCamelCase__ ( self :List[Any] , __magic_name__ :List[int] ): '''simple docstring''' if len(__magic_name__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase__ ( self :str , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = self._add_eos_if_not_present(__magic_name__ ) if token_ids_a is None: return token_ids_a else: a = self._add_eos_if_not_present(__magic_name__ ) return token_ids_a + token_ids_a def __getstate__( self :Dict ): '''simple docstring''' a = self.__dict__.copy() a = None return state def __setstate__( self :str , __magic_name__ :List[str] ): '''simple docstring''' a = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): a = {} a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase__ ( self :Any , __magic_name__ :"TextInput" , **__magic_name__ :int ): '''simple docstring''' if not self.legacy: a = SPIECE_UNDERLINE + text.replace(__magic_name__ , """ """ ) return super().tokenize(__magic_name__ , **__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Any , **__magic_name__ :Any ): '''simple docstring''' if not self.legacy: a = text.startswith(__magic_name__ ) if is_first: a = text[1:] a = self.sp_model.encode(__magic_name__ , out_type=__magic_name__ ) if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(__magic_name__ ): a = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def lowerCamelCase__ ( self :str , __magic_name__ :Tuple ): '''simple docstring''' if token.startswith("""<extra_id_""" ): a = re.match(r"""<extra_id_(\d+)>""" , __magic_name__ ) a = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(__magic_name__ ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Any ): '''simple docstring''' if index < self.sp_model.get_piece_size(): a = self.sp_model.IdToPiece(__magic_name__ ) else: a = F'<extra_id_{self.vocab_size - 1 - index}>' return token def lowerCamelCase__ ( self :Dict , __magic_name__ :Tuple ): '''simple docstring''' a = [] a = """""" a = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__magic_name__ ) + token a = True a = [] else: current_sub_tokens.append(__magic_name__ ) a = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def lowerCamelCase__ ( self :Any , __magic_name__ :str , __magic_name__ :Optional[str] = None ): '''simple docstring''' if not os.path.isdir(__magic_name__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a = os.path.join( __magic_name__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__ , """wb""" ) as fi: a = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,)
347
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Tuple=13 , __magic_name__ :List[Any]=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :List[str]=True , __magic_name__ :str=99 , __magic_name__ :Optional[Any]=32 , __magic_name__ :Union[str, Any]=5 , __magic_name__ :Any=4 , __magic_name__ :int=37 , __magic_name__ :Tuple="gelu" , __magic_name__ :List[str]=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :Tuple=512 , __magic_name__ :Dict=16 , __magic_name__ :Optional[int]=2 , __magic_name__ :Optional[int]=0.02 , __magic_name__ :Optional[Any]=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :int ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = True a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = FlaxRobertaModelTester(self ) @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""roberta-base""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ )
347
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_swiftformer": [ "SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SwiftFormerConfig", "SwiftFormerOnnxConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ "SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "SwiftFormerForImageClassification", "SwiftFormerModel", "SwiftFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys __UpperCamelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __UpperCamelCase : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): UpperCamelCase__ = None UpperCamelCase__ = "utf-8" UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = True # deprecated UpperCamelCase__ = None # deprecated UpperCamelCase__ = 10 << 20 # 10MB UpperCamelCase__ = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): UpperCamelCase__ = JsonConfig def lowerCamelCase__ ( self :str ): '''simple docstring''' if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) a = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__magic_name__ , (str, list, tuple) ): a = data_files if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] a = [] for split_name, files in data_files.items(): if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] splits.append(datasets.SplitGenerator(name=__magic_name__ , gen_kwargs={"""files""": files} ) ) return splits def lowerCamelCase__ ( self :List[str] , __magic_name__ :pa.Table ): '''simple docstring''' if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): a = self.config.features.arrow_schema.field(__magic_name__ ).type a = pa_table.append_column(__magic_name__ , pa.array([None] * len(__magic_name__ ) , type=__magic_name__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example a = table_cast(__magic_name__ , self.config.features.arrow_schema ) return pa_table def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Union[str, Any] ): '''simple docstring''' for file_idx, file in enumerate(itertools.chain.from_iterable(__magic_name__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) # We keep only the field we are interested in a = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__magic_name__ , (list, tuple) ): a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} else: a = dataset a = pa.Table.from_pydict(__magic_name__ ) yield file_idx, self._cast_table(__magic_name__ ) # If the file has one json object per line else: with open(__magic_name__ , """rb""" ) as f: a = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small a = max(self.config.chunksize // 32 , 16 << 10 ) a = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: a = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__magic_name__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": a = batch.decode(self.config.encoding , errors=__magic_name__ ).encode("""utf-8""" ) try: while True: try: a = paj.read_json( io.BytesIO(__magic_name__ ) , read_options=paj.ReadOptions(block_size=__magic_name__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__magic_name__ , pa.ArrowInvalid ) and "straddling" not in str(__magic_name__ ) or block_size > len(__magic_name__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F'Batch of {len(__magic_name__ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( __magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) except json.JSONDecodeError: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__magic_name__ , __magic_name__ ): # list is the only sequence type supported in JSON try: a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} a = pa.Table.from_pydict(__magic_name__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError(F'Not able to read records in the JSON file at {file}.' ) from None yield file_idx, self._cast_table(__magic_name__ ) break else: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError( F'Not able to read records in the JSON file at {file}. ' F'You should probably indicate the field of the JSON file containing your records. ' F'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ' F'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__magic_name__ ) batch_idx += 1
347
1
from __future__ import annotations import queue class __lowerCAmelCase : def __init__( self :Union[str, Any] , __magic_name__ :Optional[Any] ): '''simple docstring''' a = data a = None a = None def __A ( ) -> TreeNode: print("""\n********Press N to stop entering at any point of time********\n""" ) a = input("""Enter the value of the root node: """ ).strip().lower() a = queue.Queue() a = TreeNode(int(__lowerCamelCase ) ) q.put(__lowerCamelCase ) while not q.empty(): a = q.get() a = f'Enter the left node of {node_found.data}: ' a = input(__lowerCamelCase ).strip().lower() or """n""" if check == "n": return tree_node a = TreeNode(int(__lowerCamelCase ) ) a = left_node q.put(__lowerCamelCase ) a = f'Enter the right node of {node_found.data}: ' a = input(__lowerCamelCase ).strip().lower() or """n""" if check == "n": return tree_node a = TreeNode(int(__lowerCamelCase ) ) a = right_node q.put(__lowerCamelCase ) raise def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return a = queue.Queue() q.put(__lowerCamelCase ) while not q.empty(): a = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return a = queue.Queue() q.put(__lowerCamelCase ) while not q.empty(): a = [] while not q.empty(): a = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__lowerCamelCase ) def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return a = [] a = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__lowerCamelCase ) a = n.left # end of while means current node doesn't have left child a = stack.pop() # start to traverse its right child a = n.right def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return a = [] a = node while n or stack: while n: stack.append(__lowerCamelCase ) a = n.left a = stack.pop() print(n.data , end=""",""" ) a = n.right def __A ( __lowerCamelCase ) -> None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return a , a = [], [] a = node stacka.append(__lowerCamelCase ) while stacka: # to find the reversed order of post order, store it in stack2 a = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__lowerCamelCase ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def __A ( __lowerCamelCase = "" , __lowerCamelCase=50 , __lowerCamelCase="*" ) -> str: if not s: return "\n" + width * char a , a = divmod(width - len(__lowerCamelCase ) - 2 , 2 ) return f'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("Binary Tree Traversals")) __UpperCamelCase : TreeNode = build_tree() print(prompt("Pre Order Traversal")) pre_order(node) print(prompt() + "\n") print(prompt("In Order Traversal")) in_order(node) print(prompt() + "\n") print(prompt("Post Order Traversal")) post_order(node) print(prompt() + "\n") print(prompt("Level Order Traversal")) level_order(node) print(prompt() + "\n") print(prompt("Actual Level Order Traversal")) level_order_actual(node) print("*" * 50 + "\n") print(prompt("Pre Order Traversal - Iteration Version")) pre_order_iter(node) print(prompt() + "\n") print(prompt("In Order Traversal - Iteration Version")) in_order_iter(node) print(prompt() + "\n") print(prompt("Post Order Traversal - Iteration Version")) post_order_iter(node) print(prompt())
347
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :List[str] , __magic_name__ :int="</s>" , __magic_name__ :List[Any]="<unk>" , __magic_name__ :Optional[Any]="<pad>" , __magic_name__ :Optional[int]=125 , __magic_name__ :List[str]=None , **__magic_name__ :List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: a = [F'<extra_id_{i}>' for i in range(__magic_name__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens a = len(set(filter(lambda __magic_name__ : bool("""extra_id""" in str(__magic_name__ ) ) , __magic_name__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to ByT5Tokenizer. In this case the additional_special_tokens must include the""" """ extra_ids tokens""" ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token super().__init__( eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , extra_ids=__magic_name__ , additional_special_tokens=__magic_name__ , **__magic_name__ , ) a = extra_ids a = 2**8 # utf is 8 bits # define special tokens dict a = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } a = len(self.special_tokens_encoder ) a = len(__magic_name__ ) for i, token in enumerate(__magic_name__ ): a = self.vocab_size + i - n a = {v: k for k, v in self.special_tokens_encoder.items()} @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def lowerCamelCase__ ( self :Any , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None , __magic_name__ :bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__magic_name__ )) + [1] return ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def lowerCamelCase__ ( self :str , __magic_name__ :List[int] ): '''simple docstring''' if len(__magic_name__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = self._add_eos_if_not_present(__magic_name__ ) if token_ids_a is None: return token_ids_a else: a = self._add_eos_if_not_present(__magic_name__ ) return token_ids_a + token_ids_a def lowerCamelCase__ ( self :List[str] , __magic_name__ :str ): '''simple docstring''' a = [chr(__magic_name__ ) for i in text.encode("""utf-8""" )] return tokens def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if token in self.special_tokens_encoder: a = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: a = self.added_tokens_encoder[token] elif len(__magic_name__ ) != 1: a = self.unk_token_id else: a = ord(__magic_name__ ) + self._num_special_tokens return token_id def lowerCamelCase__ ( self :List[str] , __magic_name__ :Dict ): '''simple docstring''' if index in self.special_tokens_decoder: a = self.special_tokens_decoder[index] else: a = chr(index - self._num_special_tokens ) return token def lowerCamelCase__ ( self :Tuple , __magic_name__ :Optional[int] ): '''simple docstring''' a = b"""""" for token in tokens: if token in self.special_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.added_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.special_tokens_encoder: a = token.encode("""utf-8""" ) elif token in self.added_tokens_encoder: a = token.encode("""utf-8""" ) else: a = bytes([ord(__magic_name__ )] ) bstring += tok_string a = bstring.decode("""utf-8""" , errors="""ignore""" ) return string def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :str , __magic_name__ :Optional[str] = None ): '''simple docstring''' return ()
347
1
def __A ( __lowerCamelCase ) -> bool: if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError("""Input series is not valid, valid series - [2, 4, 6]""" ) if len(__lowerCamelCase ) == 0: raise ValueError("""Input list must be a non empty list""" ) if len(__lowerCamelCase ) == 1: return True a = series[1] - series[0] for index in range(len(__lowerCamelCase ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def __A ( __lowerCamelCase ) -> float: if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError("""Input series is not valid, valid series - [2, 4, 6]""" ) if len(__lowerCamelCase ) == 0: raise ValueError("""Input list must be a non empty list""" ) a = 0 for val in series: answer += val return answer / len(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
347
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __lowerCAmelCase : def __init__( self :Optional[int] , __magic_name__ :str , __magic_name__ :int=2 , __magic_name__ :List[str]=3 , __magic_name__ :Optional[int]=4 , __magic_name__ :str=2 , __magic_name__ :Any=7 , __magic_name__ :Optional[Any]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Dict=True , __magic_name__ :List[Any]=99 , __magic_name__ :Dict=36 , __magic_name__ :Optional[Any]=3 , __magic_name__ :str=4 , __magic_name__ :Optional[Any]=37 , __magic_name__ :Dict="gelu" , __magic_name__ :Any=0.1 , __magic_name__ :Union[str, Any]=0.1 , __magic_name__ :Dict=512 , __magic_name__ :str=16 , __magic_name__ :List[Any]=2 , __magic_name__ :Tuple=0.02 , __magic_name__ :Any=6 , __magic_name__ :Optional[int]=6 , __magic_name__ :Tuple=3 , __magic_name__ :str=4 , __magic_name__ :List[str]=None , __magic_name__ :str=1000 , ): '''simple docstring''' a = parent a = batch_size a = num_channels a = image_size a = patch_size a = text_seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = coordinate_size a = shape_size a = num_labels a = num_choices a = scope a = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) a = text_seq_length a = (image_size // patch_size) ** 2 + 1 a = self.text_seq_length + self.image_seq_length def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) a = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a = bbox[i, j, 3] a = bbox[i, j, 1] a = t if bbox[i, j, 2] < bbox[i, j, 0]: a = bbox[i, j, 2] a = bbox[i, j, 0] a = t a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.text_seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) a = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def lowerCamelCase__ ( self :int , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :List[str] , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int , __magic_name__ :Tuple , __magic_name__ :int ): '''simple docstring''' a = LayoutLMvaModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # text + image a = model(__magic_name__ , pixel_values=__magic_name__ ) a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , token_type_ids=__magic_name__ ) a = model(__magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only a = model(__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only a = model(pixel_values=__magic_name__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :List[Any] , __magic_name__ :Optional[int] , __magic_name__ :Tuple , __magic_name__ :Union[str, Any] , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :List[str] , __magic_name__ :List[str] ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :Dict , __magic_name__ :Optional[Any] , __magic_name__ :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :int , __magic_name__ :List[str] , __magic_name__ :Tuple ): '''simple docstring''' a = self.num_labels a = LayoutLMvaForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Tuple , __magic_name__ :str , __magic_name__ :int , __magic_name__ :Optional[int] , __magic_name__ :str , __magic_name__ :List[str] , __magic_name__ :Optional[int] , __magic_name__ :Optional[Any] ): '''simple docstring''' a = LayoutLMvaForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() a = model( __magic_name__ , bbox=__magic_name__ , pixel_values=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase__ = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :Optional[Any] , __magic_name__ :List[str] , __magic_name__ :List[Any] ): '''simple docstring''' return True def lowerCamelCase__ ( self :int ): '''simple docstring''' a = LayoutLMvaModelTester(self ) a = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :Dict , __magic_name__ :Dict , __magic_name__ :Any=False ): '''simple docstring''' a = copy.deepcopy(__magic_name__ ) if model_class in get_values(__magic_name__ ): a = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__magic_name__ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__magic_name__ ): a = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in get_values(__magic_name__ ): a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) elif model_class in [ *get_values(__magic_name__ ), ]: a = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__magic_name__ , ) return inputs_dict def lowerCamelCase__ ( self :str ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a = type self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def lowerCamelCase__ ( self :int ): '''simple docstring''' for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = LayoutLMvaModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def __A ( ) -> str: a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=__magic_name__ ) if is_vision_available() else None @slow def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(__magic_name__ ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__magic_name__ , return_tensors="""pt""" ).pixel_values.to(__magic_name__ ) a = torch.tensor([[1, 2]] ) a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass a = model( input_ids=input_ids.to(__magic_name__ ) , bbox=bbox.to(__magic_name__ ) , pixel_values=pixel_values.to(__magic_name__ ) , ) # verify the logits a = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __magic_name__ ) a = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
from collections import Counter from timeit import timeit def __A ( __lowerCamelCase = "" , ) -> bool: return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2 def __A ( __lowerCamelCase = "" ) -> bool: if len(__lowerCamelCase ) == 0: return True a = input_str.replace(""" """ , """""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string a = {} for character in lower_case_input_str: a = character_freq_dict.get(__lowerCamelCase , 0 ) + 1 a = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def __A ( __lowerCamelCase = "" ) -> None: print("""\nFor string = """ , __lowerCamelCase , """:""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(__lowerCamelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) print( """> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(__lowerCamelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) if __name__ == "__main__": __UpperCamelCase : Tuple = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) __UpperCamelCase : str = can_string_be_rearranged_as_palindrome_counter(check_str) print(F'{check_str} can {"" if status else "not "}be rearranged as a palindrome')
347
from copy import deepcopy class __lowerCAmelCase : def __init__( self :Union[str, Any] , __magic_name__ :list[int] | None = None , __magic_name__ :int | None = None ): '''simple docstring''' if arr is None and size is not None: a = size a = [0] * size elif arr is not None: self.init(__magic_name__ ) else: raise ValueError("""Either arr or size must be specified""" ) def lowerCamelCase__ ( self :Dict , __magic_name__ :list[int] ): '''simple docstring''' a = len(__magic_name__ ) a = deepcopy(__magic_name__ ) for i in range(1 , self.size ): a = self.next_(__magic_name__ ) if j < self.size: self.tree[j] += self.tree[i] def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): a = self.next_(__magic_name__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index + (index & (-index)) @staticmethod def lowerCamelCase__ ( __magic_name__ :int ): '''simple docstring''' return index - (index & (-index)) def lowerCamelCase__ ( self :Any , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value a = self.next_(__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' self.add(__magic_name__ , value - self.get(__magic_name__ ) ) def lowerCamelCase__ ( self :int , __magic_name__ :int ): '''simple docstring''' if right == 0: return 0 a = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] a = self.prev(__magic_name__ ) return result def lowerCamelCase__ ( self :int , __magic_name__ :int , __magic_name__ :int ): '''simple docstring''' return self.prefix(__magic_name__ ) - self.prefix(__magic_name__ ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :int ): '''simple docstring''' return self.query(__magic_name__ , index + 1 ) def lowerCamelCase__ ( self :Dict , __magic_name__ :int ): '''simple docstring''' value -= self.tree[0] if value < 0: return -1 a = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 a = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
347
1
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __UpperCamelCase : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): UpperCamelCase__ = None UpperCamelCase__ = "utf-8" UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = True # deprecated UpperCamelCase__ = None # deprecated UpperCamelCase__ = 10 << 20 # 10MB UpperCamelCase__ = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): UpperCamelCase__ = JsonConfig def lowerCamelCase__ ( self :str ): '''simple docstring''' if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) a = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__magic_name__ , (str, list, tuple) ): a = data_files if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] a = [] for split_name, files in data_files.items(): if isinstance(__magic_name__ , __magic_name__ ): a = [files] a = [dl_manager.iter_files(__magic_name__ ) for file in files] splits.append(datasets.SplitGenerator(name=__magic_name__ , gen_kwargs={"""files""": files} ) ) return splits def lowerCamelCase__ ( self :List[str] , __magic_name__ :pa.Table ): '''simple docstring''' if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): a = self.config.features.arrow_schema.field(__magic_name__ ).type a = pa_table.append_column(__magic_name__ , pa.array([None] * len(__magic_name__ ) , type=__magic_name__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example a = table_cast(__magic_name__ , self.config.features.arrow_schema ) return pa_table def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :Union[str, Any] ): '''simple docstring''' for file_idx, file in enumerate(itertools.chain.from_iterable(__magic_name__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) # We keep only the field we are interested in a = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__magic_name__ , (list, tuple) ): a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} else: a = dataset a = pa.Table.from_pydict(__magic_name__ ) yield file_idx, self._cast_table(__magic_name__ ) # If the file has one json object per line else: with open(__magic_name__ , """rb""" ) as f: a = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small a = max(self.config.chunksize // 32 , 16 << 10 ) a = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: a = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__magic_name__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": a = batch.decode(self.config.encoding , errors=__magic_name__ ).encode("""utf-8""" ) try: while True: try: a = paj.read_json( io.BytesIO(__magic_name__ ) , read_options=paj.ReadOptions(block_size=__magic_name__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__magic_name__ , pa.ArrowInvalid ) and "straddling" not in str(__magic_name__ ) or block_size > len(__magic_name__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F'Batch of {len(__magic_name__ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( __magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__magic_name__ ) except json.JSONDecodeError: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__magic_name__ , __magic_name__ ): # list is the only sequence type supported in JSON try: a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} a = pa.Table.from_pydict(__magic_name__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError(F'Not able to read records in the JSON file at {file}.' ) from None yield file_idx, self._cast_table(__magic_name__ ) break else: logger.error(F'Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}' ) raise ValueError( F'Not able to read records in the JSON file at {file}. ' F'You should probably indicate the field of the JSON file containing your records. ' F'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ' F'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__magic_name__ ) batch_idx += 1
347
from __future__ import annotations from typing import Generic, TypeVar __UpperCamelCase : Union[str, Any] = TypeVar("T") class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple , __magic_name__ :T ): '''simple docstring''' a = data a = self a = 0 class __lowerCAmelCase ( Generic[T] ): def __init__( self :Tuple ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T ): '''simple docstring''' a = DisjointSetTreeNode(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :T ): '''simple docstring''' a = self.map[data] if elem_ref != elem_ref.parent: a = self.find_set(elem_ref.parent.data ) return elem_ref.parent def lowerCamelCase__ ( self :List[Any] , __magic_name__ :DisjointSetTreeNode[T] , __magic_name__ :DisjointSetTreeNode[T] ): '''simple docstring''' if nodea.rank > nodea.rank: a = nodea else: a = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :T , __magic_name__ :T ): '''simple docstring''' self.link(self.find_set(__magic_name__ ) , self.find_set(__magic_name__ ) ) class __lowerCAmelCase ( Generic[T] ): def __init__( self :Union[str, Any] ): '''simple docstring''' a = {} def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :T ): '''simple docstring''' if node not in self.connections: a = {} def lowerCamelCase__ ( self :Any , __magic_name__ :T , __magic_name__ :T , __magic_name__ :int ): '''simple docstring''' self.add_node(__magic_name__ ) self.add_node(__magic_name__ ) a = weight a = weight def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] a = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda __magic_name__ : x[2] ) # creating the disjoint set a = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__magic_name__ ) # MST generation a = 0 a = 0 a = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: a , a , a = edges[index] index += 1 a = disjoint_set.find_set(__magic_name__ ) a = disjoint_set.find_set(__magic_name__ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__magic_name__ , __magic_name__ , __magic_name__ ) disjoint_set.union(__magic_name__ , __magic_name__ ) return graph
347
1
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = 42 @flax_register_to_config class __lowerCAmelCase ( nn.Module , __magic_name__ , __magic_name__ ): UpperCamelCase__ = 32 UpperCamelCase__ = 4 UpperCamelCase__ = 4 UpperCamelCase__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) UpperCamelCase__ = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") UpperCamelCase__ = False UpperCamelCase__ = (320, 640, 1280, 1280) UpperCamelCase__ = 2 UpperCamelCase__ = 8 UpperCamelCase__ = None UpperCamelCase__ = 1280 UpperCamelCase__ = 0.0 UpperCamelCase__ = False UpperCamelCase__ = jnp.floataa UpperCamelCase__ = True UpperCamelCase__ = 0 UpperCamelCase__ = False def lowerCamelCase__ ( self :List[str] , __magic_name__ :jax.random.KeyArray ): '''simple docstring''' a = (1, self.in_channels, self.sample_size, self.sample_size) a = jnp.zeros(__magic_name__ , dtype=jnp.floataa ) a = jnp.ones((1,) , dtype=jnp.intaa ) a = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) a , a = jax.random.split(__magic_name__ ) a = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ )["params"] def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.block_out_channels a = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.""" ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. a = self.num_attention_heads or self.attention_head_dim # input a = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time a = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) a = FlaxTimestepEmbedding(__magic_name__ , dtype=self.dtype ) a = self.only_cross_attention if isinstance(__magic_name__ , __magic_name__ ): a = (only_cross_attention,) * len(self.down_block_types ) if isinstance(__magic_name__ , __magic_name__ ): a = (num_attention_heads,) * len(self.down_block_types ) # down a = [] a = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): a = output_channel a = block_out_channels[i] a = i == len(__magic_name__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": a = FlaxCrossAttnDownBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: a = FlaxDownBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__magic_name__ ) a = down_blocks # mid a = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up a = [] a = list(reversed(__magic_name__ ) ) a = list(reversed(__magic_name__ ) ) a = list(reversed(__magic_name__ ) ) a = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): a = output_channel a = reversed_block_out_channels[i] a = reversed_block_out_channels[min(i + 1 , len(__magic_name__ ) - 1 )] a = i == len(__magic_name__ ) - 1 if up_block_type == "CrossAttnUpBlock2D": a = FlaxCrossAttnUpBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , prev_output_channel=__magic_name__ , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: a = FlaxUpBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , prev_output_channel=__magic_name__ , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(__magic_name__ ) a = output_channel a = up_blocks # out a = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) a = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self :List[str] , __magic_name__ :Union[str, Any] , __magic_name__ :Optional[Any] , __magic_name__ :str , __magic_name__ :Tuple=None , __magic_name__ :List[str]=None , __magic_name__ :bool = True , __magic_name__ :bool = False , ): '''simple docstring''' if not isinstance(__magic_name__ , jnp.ndarray ): a = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__magic_name__ , jnp.ndarray ) and len(timesteps.shape ) == 0: a = timesteps.astype(dtype=jnp.floataa ) a = jnp.expand_dims(__magic_name__ , 0 ) a = self.time_proj(__magic_name__ ) a = self.time_embedding(__magic_name__ ) # 2. pre-process a = jnp.transpose(__magic_name__ , (0, 2, 3, 1) ) a = self.conv_in(__magic_name__ ) # 3. down a = (sample,) for down_block in self.down_blocks: if isinstance(__magic_name__ , __magic_name__ ): a , a = down_block(__magic_name__ , __magic_name__ , __magic_name__ , deterministic=not train ) else: a , a = down_block(__magic_name__ , __magic_name__ , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: a = () for down_block_res_sample, down_block_additional_residual in zip( __magic_name__ , __magic_name__ ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) a = new_down_block_res_samples # 4. mid a = self.mid_block(__magic_name__ , __magic_name__ , __magic_name__ , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: a = down_block_res_samples[-(self.layers_per_block + 1) :] a = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(__magic_name__ , __magic_name__ ): a = up_block( __magic_name__ , temb=__magic_name__ , encoder_hidden_states=__magic_name__ , res_hidden_states_tuple=__magic_name__ , deterministic=not train , ) else: a = up_block(__magic_name__ , temb=__magic_name__ , res_hidden_states_tuple=__magic_name__ , deterministic=not train ) # 6. post-process a = self.conv_norm_out(__magic_name__ ) a = nn.silu(__magic_name__ ) a = self.conv_out(__magic_name__ ) a = jnp.transpose(__magic_name__ , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=__magic_name__ )
347
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = tempfile.mkdtemp() a = BlipImageProcessor() a = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) a = BlipProcessor(__magic_name__ , __magic_name__ ) processor.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self :List[Any] , **__magic_name__ :Union[str, Any] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).tokenizer def lowerCamelCase__ ( self :str , **__magic_name__ :List[str] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ).image_processor def lowerCamelCase__ ( self :int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__magic_name__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) a = self.get_image_processor(do_normalize=__magic_name__ , padding_value=1.0 ) a = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__magic_name__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __magic_name__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = self.prepare_image_inputs() a = image_processor(__magic_name__ , return_tensors="""np""" ) a = processor(images=__magic_name__ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = processor(text=__magic_name__ ) a = tokenizer(__magic_name__ , return_token_type_ids=__magic_name__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(__magic_name__ ): processor() def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__magic_name__ ) a = tokenizer.batch_decode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) a = """lower newer""" a = self.prepare_image_inputs() a = processor(text=__magic_name__ , images=__magic_name__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
347
1
def __A ( __lowerCamelCase ) -> bool: a = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def __A ( __lowerCamelCase = 5000 ) -> int: a = [(i * (3 * i - 1)) // 2 for i in range(1 , __lowerCamelCase )] for i, pentagonal_i in enumerate(__lowerCamelCase ): for j in range(__lowerCamelCase , len(__lowerCamelCase ) ): a = pentagonal_nums[j] a = pentagonal_i + pentagonal_j a = pentagonal_j - pentagonal_i if is_pentagonal(__lowerCamelCase ) and is_pentagonal(__lowerCamelCase ): return b return -1 if __name__ == "__main__": print(F'{solution() = }')
347
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : int = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class __lowerCAmelCase ( __magic_name__ , __magic_name__ ): UpperCamelCase__ = '''nat''' UpperCamelCase__ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self :Any , __magic_name__ :int=4 , __magic_name__ :Dict=3 , __magic_name__ :List[str]=64 , __magic_name__ :Optional[int]=[3, 4, 6, 5] , __magic_name__ :int=[2, 4, 8, 16] , __magic_name__ :str=7 , __magic_name__ :Tuple=3.0 , __magic_name__ :Dict=True , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.0 , __magic_name__ :List[Any]=0.1 , __magic_name__ :Optional[Any]="gelu" , __magic_name__ :Optional[Any]=0.02 , __magic_name__ :Tuple=1E-5 , __magic_name__ :Union[str, Any]=0.0 , __magic_name__ :int=None , __magic_name__ :Any=None , **__magic_name__ :Dict , ): '''simple docstring''' super().__init__(**__magic_name__ ) a = patch_size a = num_channels a = embed_dim a = depths a = len(__magic_name__ ) a = num_heads a = kernel_size a = mlp_ratio a = qkv_bias a = hidden_dropout_prob a = attention_probs_dropout_prob a = drop_path_rate a = hidden_act a = layer_norm_eps a = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model a = int(embed_dim * 2 ** (len(__magic_name__ ) - 1) ) a = layer_scale_init_value a = ["""stem"""] + [F'stage{idx}' for idx in range(1 , len(__magic_name__ ) + 1 )] a , a = get_aligned_output_features_output_indices( out_features=__magic_name__ , out_indices=__magic_name__ , stage_names=self.stage_names )
347
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :List[Any] , __magic_name__ :int , __magic_name__ :int=7 , __magic_name__ :Optional[Any]=3 , __magic_name__ :Dict=18 , __magic_name__ :Optional[Any]=30 , __magic_name__ :Optional[Any]=400 , __magic_name__ :Dict=True , __magic_name__ :List[str]=32 , __magic_name__ :Union[str, Any]=True , ): '''simple docstring''' a = parent a = batch_size a = num_channels a = image_size a = min_resolution a = max_resolution a = do_resize a = size_divisor a = do_rescale def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = GLPNImageProcessor if is_vision_available() else None def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = GLPNImageProcessingTester(self ) @property def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase__ ( self :str ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , """do_resize""" ) ) self.assertTrue(hasattr(__magic_name__ , """size_divisor""" ) ) self.assertTrue(hasattr(__magic_name__ , """resample""" ) ) self.assertTrue(hasattr(__magic_name__ , """do_rescale""" ) ) def lowerCamelCase__ ( self :str ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) a = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) a = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) a = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
347
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __A ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer a = flax_key_tuple[:-1] + ("""weight""",) a = torch.permute(__lowerCamelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCamelCase ): # linear layer a = flax_key_tuple[:-1] + ("""weight""",) a = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: a = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: if "metadata" in layer: a = layer.split("""metadata""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: a = layer.split("""kvstore""" ) a = """""".join(split_layer[0] )[:-1] a = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: a = layer.split("""/""" ) a = """/""".join(split_layer[:-1] ) a = (split_layer[-1],) if "kvstore/path" in layer: a = f'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: a = """file""" else: a = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __A ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: a = rename_keys(__lowerCamelCase ) a = {} for k, v in current_block.items(): a = v a = new_current_block torch.save(__lowerCamelCase , __lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = WEIGHTS_NAME ) -> List[str]: a = convert_file_size_to_int(__lowerCamelCase ) a = [] a = {} a = 0 a = 0 os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: a = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] a = flatten_dict(__lowerCamelCase , sep="""/""" ) a = {} for layer in checkpoint_info.keys(): a , a , a = get_key_and_tensorstore_dict( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if curr_real_layer_name in all_layers: a = content else: a = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() a = torch.tensor(__lowerCamelCase ) a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts a , a = rename_base_flax_keys(tuple(key.split("""/""" ) ) , __lowerCamelCase ) a = """/""".join(__lowerCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: a = os.path.join( __lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block a = {} a = 0 a = raw_weights.to(getattr(__lowerCamelCase , __lowerCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{len(__lowerCamelCase )+1:05d}-of-???.bin' ) ) rename_and_save_block(__lowerCamelCase , __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index a = {} a = {} for idx, shard in enumerate(__lowerCamelCase ): a = weights_name.replace( """.bin""" , f'-{idx+1:05d}-of-{len(__lowerCamelCase ):05d}.bin' ) # len(sharded_state_dicts):05d} a = os.path.join(__lowerCamelCase , weights_name.replace(""".bin""" , f'-{idx+1:05d}-of-???.bin' ) ) os.rename(__lowerCamelCase , os.path.join(__lowerCamelCase , __lowerCamelCase ) ) a = shard for key in shard: a = shard_file # Add the metadata a = {"""total_size""": total_size} a = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(__lowerCamelCase , __lowerCamelCase ) , """w""" , encoding="""utf-8""" ) as f: a = json.dumps(__lowerCamelCase , indent=2 , sort_keys=__lowerCamelCase ) + """\n""" f.write(__lowerCamelCase ) return metadata, index if __name__ == "__main__": __UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __UpperCamelCase : Any = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __A ( ) -> Tuple: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer a = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) a = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) a = TaTokenizer.from_pretrained("""t5-small""" ) a = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" a = tokenizer(__lowerCamelCase , return_tensors="""pt""" ).input_ids a = model.generate(__lowerCamelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
347
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __UpperCamelCase : Union[str, Any] = (720, 1_280) # Height, Width __UpperCamelCase : Any = (0.4, 0.6) # if height or width lower than this scale, drop it. __UpperCamelCase : str = 1 / 100 __UpperCamelCase : Optional[int] = "" __UpperCamelCase : List[Any] = "" __UpperCamelCase : Union[str, Any] = "" __UpperCamelCase : Tuple = 250 def __A ( ) -> None: a , a = get_dataset(__lowerCamelCase , __lowerCamelCase ) for index in range(__lowerCamelCase ): a = random.sample(range(len(__lowerCamelCase ) ) , 4 ) a , a , a = update_image_and_anno( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , filter_scale=__lowerCamelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' a = random_chars(32 ) a = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] a = f'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(f'{file_root}.jpg' , __lowerCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) a = [] for anno in new_annos: a = anno[3] - anno[1] a = anno[4] - anno[2] a = anno[1] + width / 2 a = anno[2] + height / 2 a = f'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(__lowerCamelCase ) with open(f'{file_root}.txt' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> tuple[list, list]: a = [] a = [] for label_file in glob.glob(os.path.join(__lowerCamelCase , """*.txt""" ) ): a = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCamelCase ) as in_file: a = in_file.readlines() a = os.path.join(__lowerCamelCase , f'{label_name}.jpg' ) a = [] for obj_list in obj_lists: a = obj_list.rstrip("""\n""" ).split(""" """ ) a = float(obj[1] ) - float(obj[3] ) / 2 a = float(obj[2] ) - float(obj[4] ) / 2 a = float(obj[1] ) + float(obj[3] ) / 2 a = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__lowerCamelCase ) labels.append(__lowerCamelCase ) return img_paths, labels def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 0.0 , ) -> tuple[list, list, str]: a = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) a = int(scale_x * output_size[1] ) a = int(scale_y * output_size[0] ) a = [] a = [] for i, index in enumerate(__lowerCamelCase ): a = all_img_list[index] path_list.append(__lowerCamelCase ) a = all_annos[index] a = cva.imread(__lowerCamelCase ) if i == 0: # top-left a = cva.resize(__lowerCamelCase , (divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = bbox[2] * scale_y a = bbox[3] * scale_x a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right a = cva.resize(__lowerCamelCase , (output_size[1] - divid_point_x, divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = bbox[2] * scale_y a = scale_x + bbox[3] * (1 - scale_x) a = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left a = cva.resize(__lowerCamelCase , (divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = bbox[1] * scale_x a = scale_y + bbox[2] * (1 - scale_y) a = bbox[3] * scale_x a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right a = cva.resize( __lowerCamelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) a = img for bbox in img_annos: a = scale_x + bbox[1] * (1 - scale_x) a = scale_y + bbox[2] * (1 - scale_y) a = scale_x + bbox[3] * (1 - scale_x) a = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: a = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __A ( __lowerCamelCase ) -> str: assert number_char > 1, "The number of character should greater than 1" a = ascii_lowercase + digits return "".join(random.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
347
1
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __UpperCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--original_config_file", type=str, required=True, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--image_size", default=512, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") def __A ( __lowerCamelCase ) -> Union[str, Any]: if string == "True": return True elif string == "False": return False else: raise ValueError(f'could not parse string as bool {string}' ) parser.add_argument( "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool ) parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int) __UpperCamelCase : Optional[Any] = parser.parse_args() __UpperCamelCase : Dict = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
347
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Optional[Any] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "MobileNetV2OnnxConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ["MobileNetV2FeatureExtractor"] __UpperCamelCase : Tuple = ["MobileNetV2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV2ForImageClassification", "MobileNetV2ForSemanticSegmentation", "MobileNetV2Model", "MobileNetV2PreTrainedModel", "load_tf_weights_in_mobilenet_v2", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
from collections.abc import Callable import numpy as np def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> np.array: a = int(np.ceil((x_end - xa) / step_size ) ) a = np.zeros((n + 1,) ) a = ya a = xa for k in range(__lowerCamelCase ): a = y[k] + step_size * ode_func(__lowerCamelCase , y[k] ) a = y[k] + ( (step_size / 2) * (ode_func(__lowerCamelCase , y[k] ) + ode_func(x + step_size , __lowerCamelCase )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
347
def __A ( __lowerCamelCase ) -> bool: if num < 0: return False a = num a = 0 while num > 0: a = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
1
from collections.abc import Iterable from typing import Any class __lowerCAmelCase : def __init__( self :List[Any] , __magic_name__ :int | None = None ): '''simple docstring''' a = value a = None # Added in order to delete a node easier a = None a = None def __repr__( self :Any ): '''simple docstring''' from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F'{self.value}': (self.left, self.right)} , indent=1 ) class __lowerCAmelCase : def __init__( self :Optional[Any] , __magic_name__ :Node | None = None ): '''simple docstring''' a = root def __str__( self :Optional[int] ): '''simple docstring''' return str(self.root ) def lowerCamelCase__ ( self :Dict , __magic_name__ :Node , __magic_name__ :Node | None ): '''simple docstring''' if new_children is not None: # reset its kids a = node.parent if node.parent is not None: # reset its parent if self.is_right(__magic_name__ ): # If it is the right children a = new_children else: a = new_children else: a = new_children def lowerCamelCase__ ( self :int , __magic_name__ :Node ): '''simple docstring''' if node.parent and node.parent.right: return node == node.parent.right return False def lowerCamelCase__ ( self :str ): '''simple docstring''' return self.root is None def lowerCamelCase__ ( self :str , __magic_name__ :List[Any] ): '''simple docstring''' a = Node(__magic_name__ ) # create a new Node if self.empty(): # if Tree is empty a = new_node # set its root else: # Tree is not empty a = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: a = new_node # We insert the new node in a leaf break else: a = parent_node.left else: if parent_node.right is None: a = new_node break else: a = parent_node.right a = parent_node def lowerCamelCase__ ( self :Optional[int] , *__magic_name__ :Optional[int] ): '''simple docstring''' for value in values: self.__insert(__magic_name__ ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :str ): '''simple docstring''' if self.empty(): raise IndexError("""Warning: Tree is empty! please use another.""" ) else: a = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: a = node.left if value < node.value else node.right return node def lowerCamelCase__ ( self :Any , __magic_name__ :Node | None = None ): '''simple docstring''' if node is None: if self.root is None: return None a = self.root if not self.empty(): while node.right is not None: a = node.right return node def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :Node | None = None ): '''simple docstring''' if node is None: a = self.root if self.root is None: return None if not self.empty(): a = self.root while node.left is not None: a = node.left return node def lowerCamelCase__ ( self :Tuple , __magic_name__ :int ): '''simple docstring''' a = self.search(__magic_name__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(__magic_name__ , __magic_name__ ) elif node.left is None: # Has only right children self.__reassign_nodes(__magic_name__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(__magic_name__ , node.left ) else: a = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore a = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def lowerCamelCase__ ( self :List[Any] , __magic_name__ :Node | None ): '''simple docstring''' if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :Any=None ): '''simple docstring''' if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :list , __magic_name__ :Node | None ): '''simple docstring''' if node: self.inorder(__magic_name__ , node.left ) arr.append(node.value ) self.inorder(__magic_name__ , node.right ) def lowerCamelCase__ ( self :List[Any] , __magic_name__ :int , __magic_name__ :Node ): '''simple docstring''' a = [] self.inorder(__magic_name__ , __magic_name__ ) # append all values to list using inorder traversal return arr[k - 1] def __A ( __lowerCamelCase ) -> list[Node]: a = [] if curr_node is not None: a = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def __A ( ) -> None: a = (8, 3, 6, 1, 10, 14, 13, 4, 7) a = BinarySearchTree() for i in testlist: t.insert(__lowerCamelCase ) # Prints all the elements of the list in order traversal print(__lowerCamelCase ) if t.search(6 ) is not None: print("""The value 6 exists""" ) else: print("""The value 6 doesn't exist""" ) if t.search(-1 ) is not None: print("""The value -1 exists""" ) else: print("""The value -1 doesn't exist""" ) if not t.empty(): print("""Max Value: """ , t.get_max().value ) # type: ignore print("""Min Value: """ , t.get_min().value ) # type: ignore for i in testlist: t.remove(__lowerCamelCase ) print(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
347
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = CanineTokenizer UpperCamelCase__ = False def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().setUp() a = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return CanineTokenizer.from_pretrained("""google/canine-s""" ) def lowerCamelCase__ ( self :Tuple , **__magic_name__ :Dict ): '''simple docstring''' a = self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) a = 1024 return tokenizer @require_torch def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.canine_tokenizer a = ["""Life is like a box of chocolates.""", """You never know what you're gonna get."""] # fmt: off a = [5_7344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 5_7345, 0, 0, 0, 0] # fmt: on a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) self.assertIsInstance(__magic_name__ , __magic_name__ ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = ["""Once there was a man.""", """He wrote a test in HuggingFace Tranformers."""] a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("""input_ids""" , __magic_name__ ) self.assertIn("""attention_mask""" , __magic_name__ ) self.assertIn("""token_type_ids""" , __magic_name__ ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = [ """What's the weater?""", """It's about 25 degrees.""", ] a = tokenizer( text_target=__magic_name__ , max_length=32 , padding="""max_length""" , truncation=__magic_name__ , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) shutil.rmtree(__magic_name__ ) a = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: a = chr(0Xe_0_0_7 ) additional_special_tokens.append(__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertIn(__magic_name__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) a = tokenizer.__class__.from_pretrained(__magic_name__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a , a = self.get_clean_sequence(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_5 a = chr(__magic_name__ ) tokenizer.add_special_tokens({"""cls_token""": special_token} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) a = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , input_encoded + special_token_id ) a = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertTrue(special_token not in decoded ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = chr(0Xe_0_0_5 ) a = chr(0Xe_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=__magic_name__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"""additional_special_tokens""": [SPECIAL_TOKEN_2]} ) a = tokenizer.tokenize(__magic_name__ ) a = tokenizer.tokenize(__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(token_a[0] , __magic_name__ ) self.assertEqual(token_a[0] , __magic_name__ ) @require_tokenizers def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(__magic_name__ ) tokenizer.from_pretrained(__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__magic_name__ ) with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = [new_token_a] a = [new_token_a] with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files a = tokenizer_class.from_pretrained(__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) a = 0Xe_0_0_7 a = chr(__magic_name__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained a = [AddedToken(__magic_name__ , lstrip=__magic_name__ )] a = tokenizer_class.from_pretrained( __magic_name__ , additional_special_tokens=__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = """hello world""" if self.space_between_special_tokens: a = """[CLS] hello world [SEP]""" else: a = input a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.decode(__magic_name__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(__magic_name__ , [output, output.lower()] ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = [ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] a = """a""" a = ord(__magic_name__ ) for attr in attributes_list: setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [] ) a = 0Xe_0_0_6 a = chr(__magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [additional_special_token_id] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [additional_special_token] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [additional_special_token_id] ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :str ): '''simple docstring''' pass def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass
347
1
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def __A ( __lowerCamelCase ) -> float: return np.dot(__lowerCamelCase , __lowerCamelCase ) class __lowerCAmelCase : def __init__( self :Optional[int] , *, __magic_name__ :float = np.inf , __magic_name__ :str = "linear" , __magic_name__ :float = 0.0 , ): '''simple docstring''' a = regularization a = gamma if kernel == "linear": a = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("""rbf kernel requires gamma""" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("""gamma must be float or int""" ) if not self.gamma > 0: raise ValueError("""gamma must be > 0""" ) a = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: a = F'Unknown kernel: {kernel}' raise ValueError(__magic_name__ ) def lowerCamelCase__ ( self :str , __magic_name__ :ndarray , __magic_name__ :ndarray ): '''simple docstring''' return np.dot(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Any , __magic_name__ :ndarray , __magic_name__ :ndarray ): '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :list[ndarray] , __magic_name__ :ndarray ): '''simple docstring''' a = observations a = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((a) , ) = np.shape(__magic_name__ ) def to_minimize(__magic_name__ :ndarray ) -> float: a = 0 ((a) , ) = np.shape(__magic_name__ ) for i in range(__magic_name__ ): for j in range(__magic_name__ ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__magic_name__ ) a = LinearConstraint(__magic_name__ , 0 , 0 ) a = Bounds(0 , self.regularization ) a = minimize( __magic_name__ , np.ones(__magic_name__ ) , bounds=__magic_name__ , constraints=[ly_contraint] ).x a = l_star # calculating mean offset of separation plane to points a = 0 for i in range(__magic_name__ ): for j in range(__magic_name__ ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) a = s / n def lowerCamelCase__ ( self :Any , __magic_name__ :ndarray ): '''simple docstring''' a = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __magic_name__ ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
347
def __A ( __lowerCamelCase ) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
347
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : List[str] = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
def __A ( __lowerCamelCase ) -> int: if not numbers: return 0 if not isinstance(__lowerCamelCase , (list, tuple) ) or not all( isinstance(__lowerCamelCase , __lowerCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) a = a = a = numbers[0] for i in range(1 , len(__lowerCamelCase ) ): # update the maximum and minimum subarray products a = numbers[i] if number < 0: a , a = min_till_now, max_till_now a = max(__lowerCamelCase , max_till_now * number ) a = min(__lowerCamelCase , min_till_now * number ) # update the maximum product found till now a = max(__lowerCamelCase , __lowerCamelCase ) return max_prod
347
1
def __A ( __lowerCamelCase = 5000_0000 ) -> int: a = set() a = int((limit - 24) ** (1 / 2) ) a = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __lowerCamelCase ) ) ) for primea in primes: a = primea * primea for primea in primes: a = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: a = primea * primea * primea * primea a = square + cube + tetr if total >= limit: break ret.add(__lowerCamelCase ) return len(__lowerCamelCase ) if __name__ == "__main__": print(F'{solution() = }')
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCamelCase : Optional[Any] = { "configuration_wav2vec2": ["WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2Config"], "feature_extraction_wav2vec2": ["Wav2Vec2FeatureExtractor"], "processing_wav2vec2": ["Wav2Vec2Processor"], "tokenization_wav2vec2": ["Wav2Vec2CTCTokenizer", "Wav2Vec2Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = [ "WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ForAudioFrameClassification", "Wav2Vec2ForCTC", "Wav2Vec2ForMaskedLM", "Wav2Vec2ForPreTraining", "Wav2Vec2ForSequenceClassification", "Wav2Vec2ForXVector", "Wav2Vec2Model", "Wav2Vec2PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ "TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWav2Vec2ForCTC", "TFWav2Vec2Model", "TFWav2Vec2PreTrainedModel", "TFWav2Vec2ForSequenceClassification", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "FlaxWav2Vec2ForCTC", "FlaxWav2Vec2ForPreTraining", "FlaxWav2Vec2Model", "FlaxWav2Vec2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( __magic_name__ , __magic_name__ , __magic_name__ , unittest.TestCase ): UpperCamelCase__ = StableDiffusionInstructPixaPixPipeline UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''cross_attention_kwargs'''} UpperCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) a = PNDMScheduler(skip_prk_steps=__magic_name__ ) torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) a = CLIPTextModel(__magic_name__ ) a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) a = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :Union[str, Any] , __magic_name__ :Union[str, Any]=0 ): '''simple docstring''' a = floats_tensor((1, 3, 32, 32) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) a = image.cpu().permute(0 , 2 , 3 , 1 )[0] a = Image.fromarray(np.uinta(__magic_name__ ) ).convert("""RGB""" ) if str(__magic_name__ ).startswith("""mps""" ): a = torch.manual_seed(__magic_name__ ) else: a = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) a = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """image_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = """cpu""" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionInstructPixaPixPipeline(**__magic_name__ ) a = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_dummy_inputs(__magic_name__ ) a = sd_pipe(**__magic_name__ ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = """cpu""" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionInstructPixaPixPipeline(**__magic_name__ ) a = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_dummy_inputs(__magic_name__ ) a = """french fries""" a = sd_pipe(**__magic_name__ , negative_prompt=__magic_name__ ) a = output.images a = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = """cpu""" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionInstructPixaPixPipeline(**__magic_name__ ) a = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_dummy_inputs(__magic_name__ ) a = [inputs["""prompt"""]] * 2 a = np.array(inputs["""image"""] ).astype(np.floataa ) / 255.0 a = torch.from_numpy(__magic_name__ ).unsqueeze(0 ).to(__magic_name__ ) a = image / 2 + 0.5 a = image.permute(0 , 3 , 1 , 2 ) a = image.repeat(2 , 1 , 1 , 1 ) a = sd_pipe(**__magic_name__ ).images a = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) a = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = """cpu""" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = EulerAncestralDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" ) a = StableDiffusionInstructPixaPixPipeline(**__magic_name__ ) a = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) a = self.get_dummy_inputs(__magic_name__ ) a = sd_pipe(**__magic_name__ ).images a = image[0, -3:, -3:, -1] a = [round(__magic_name__ , 4 ) for x in image_slice.flatten().tolist()] print(""",""".join([str(__magic_name__ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) a = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = self.get_dummy_components() a = StableDiffusionInstructPixaPixPipeline(**__magic_name__ ) a = VaeImageProcessor(do_resize=__magic_name__ , do_normalize=__magic_name__ ) a = pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) a = pipe(**self.get_dummy_inputs_by_type(__magic_name__ , input_image_type="""pt""" ) )[0] a = components["""vae"""] a = self.get_dummy_inputs_by_type(__magic_name__ , input_image_type="""pt""" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): a = vae.encode(inputs[image_param] ).latent_dist.mode() a = pipe(**__magic_name__ )[0] a = np.abs(out - out_latents_inputs ).max() self.assertLess(__magic_name__ , 1E-4 , """passing latents as image input generate different result from passing image""" ) @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self :Tuple , __magic_name__ :Optional[Any]=0 ): '''simple docstring''' a = torch.manual_seed(__magic_name__ ) a = load_image( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg""" ) a = { """prompt""": """turn him into a cyborg""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """image_guidance_scale""": 1.0, """output_type""": """numpy""", } return inputs def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing() a = self.get_inputs() a = pipe(**__magic_name__ ).images a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) a = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCamelCase__ ( self :str ): '''simple docstring''' a = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=__magic_name__ ) a = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing() a = self.get_inputs() a = pipe(**__magic_name__ ).images a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) a = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=__magic_name__ ) a = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing() a = self.get_inputs() a = pipe(**__magic_name__ ).images a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) a = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCamelCase__ ( self :int ): '''simple docstring''' a = 0 def callback_fn(__magic_name__ :int , __magic_name__ :int , __magic_name__ :torch.FloatTensor ) -> None: a = True nonlocal number_of_steps number_of_steps += 1 if step == 1: a = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) a = latents[0, -3:, -3:, -1] a = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: a = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) a = latents[0, -3:, -3:, -1] a = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 a = False a = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=__magic_name__ , torch_dtype=torch.floataa ) a = pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing() a = self.get_inputs() pipe(**__magic_name__ , callback=__magic_name__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowerCamelCase__ ( self :Any ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=__magic_name__ , torch_dtype=torch.floataa ) a = pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() a = self.get_inputs() a = pipe(**__magic_name__ ) a = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 a = inputs["""image"""].resize((504, 504) ) a = """timbrooks/instruct-pix2pix""" a = StableDiffusionInstructPixaPixPipeline.from_pretrained( __magic_name__ , safety_checker=__magic_name__ , ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing() a = pipe(**__magic_name__ ) a = output.images[0] a = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) a = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3
347
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCamelCase ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(__lowerCamelCase ) assert result == expected
347
1
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> list[float]: a , a = coefficient_matrix.shape a , a = constant_matrix.shape if rowsa != colsa: a = f'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(__lowerCamelCase ) if colsa != 1: a = f'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(__lowerCamelCase ) if rowsa != rowsa: a = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ f'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(__lowerCamelCase ) if len(__lowerCamelCase ) != rowsa: a = ( """Number of initial values must be equal to number of rows in coefficient """ f'matrix but received {len(__lowerCamelCase )} and {rowsa}' ) raise ValueError(__lowerCamelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) a = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) a , a = table.shape strictly_diagonally_dominant(__lowerCamelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCamelCase ): a = [] for row in range(__lowerCamelCase ): a = 0 for col in range(__lowerCamelCase ): if col == row: a = table[row][col] elif col == cols - 1: a = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] a = (temp + val) / denom new_val.append(__lowerCamelCase ) a = new_val return [float(__lowerCamelCase ) for i in new_val] def __A ( __lowerCamelCase ) -> bool: a , a = table.shape a = True for i in range(0 , __lowerCamelCase ): a = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
347
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __A ( __lowerCamelCase ) -> bool: a = int(number**0.5 ) return number == sq * sq def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> tuple[int, int]: a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den a = x_den * y_den * z_den a = gcd(__lowerCamelCase , __lowerCamelCase ) top //= hcf bottom //= hcf return top, bottom def __A ( __lowerCamelCase = 35 ) -> int: a = set() a = 42 a = Fraction(0 ) a = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 a = x_num * y_den + x_den * y_num a = x_den * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) a = x_den * x_den * y_den * y_den if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=-1 a = x_num * y_num a = x_den * y_num + x_num * y_den a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 a = x_num * x_num * y_num * y_num a = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): a = int(sqrt(__lowerCamelCase ) ) a = int(sqrt(__lowerCamelCase ) ) a = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: a = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) for num, den in unique_s: total += Fraction(__lowerCamelCase , __lowerCamelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(F'{solution() = }')
347
1
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = KandinskyVaaPriorPipeline UpperCamelCase__ = ['''prompt'''] UpperCamelCase__ = ['''prompt''', '''negative_prompt'''] UpperCamelCase__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] UpperCamelCase__ = False @property def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' return 32 @property def lowerCamelCase__ ( self :Any ): '''simple docstring''' return 32 @property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return self.time_input_dim @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return self.time_input_dim * 4 @property def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' return 100 @property def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' torch.manual_seed(0 ) a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__magic_name__ ) @property def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) a = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } a = PriorTransformer(**__magic_name__ ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) a = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) a = CLIPVisionModelWithProjection(__magic_name__ ) return model @property def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = CLIPImageProcessor( crop_size=224 , do_center_crop=__magic_name__ , do_normalize=__magic_name__ , do_resize=__magic_name__ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.dummy_prior a = self.dummy_image_encoder a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_image_processor a = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=__magic_name__ , clip_sample_range=10.0 , ) a = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def lowerCamelCase__ ( self :List[Any] , __magic_name__ :Optional[int] , __magic_name__ :List[Any]=0 ): '''simple docstring''' if str(__magic_name__ ).startswith("""mps""" ): a = torch.manual_seed(__magic_name__ ) else: a = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) a = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = """cpu""" a = self.get_dummy_components() a = self.pipeline_class(**__magic_name__ ) a = pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) a = pipe(**self.get_dummy_inputs(__magic_name__ ) ) a = output.image_embeds a = pipe( **self.get_dummy_inputs(__magic_name__ ) , return_dict=__magic_name__ , )[0] a = image[0, -10:] a = image_from_tuple[0, -10:] assert image.shape == (1, 32) a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = torch_device == """cpu""" a = True a = False self._test_inference_batch_single_identical( test_max_difference=__magic_name__ , relax_max_difference=__magic_name__ , test_mean_pixel_difference=__magic_name__ , ) @skip_mps def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = torch_device == """cpu""" a = False self._test_attention_slicing_forward_pass( test_max_difference=__magic_name__ , test_mean_pixel_difference=__magic_name__ , )
347
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :List[str] , __magic_name__ :List[str] , __magic_name__ :List[Any]=13 , __magic_name__ :Any=7 , __magic_name__ :Optional[int]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :Any=99 , __magic_name__ :List[str]=32 , __magic_name__ :List[str]=5 , __magic_name__ :str=4 , __magic_name__ :str=37 , __magic_name__ :Optional[int]="gelu" , __magic_name__ :int=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Tuple=16 , __magic_name__ :Tuple=2 , __magic_name__ :List[str]=0.02 , __magic_name__ :Any=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = FlaxRoFormerModelTester(self ) @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) a = jnp.array([[0, 1, 2, 3, 4, 5]] ) a = model(__magic_name__ )[0] a = 5_0000 a = (1, 6, vocab_size) self.assertEqual(output.shape , __magic_name__ ) a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : List[str] = logging.get_logger(__name__) def __A ( __lowerCamelCase , __lowerCamelCase=False ) -> str: a = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'vit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" a = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=False ) -> int: for i in range(config.num_hidden_layers ): if base_model: a = """""" else: a = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) a = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) a = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict a = in_proj_weight[ : config.hidden_size, : ] a = in_proj_bias[: config.hidden_size] a = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] a = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] a = in_proj_weight[ -config.hidden_size :, : ] a = in_proj_bias[-config.hidden_size :] def __A ( __lowerCamelCase ) -> Dict: a = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__lowerCamelCase , __lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Tuple: a = dct.pop(__lowerCamelCase ) a = val def __A ( ) -> List[Any]: a = """http://images.cocodataset.org/val2017/000000039769.jpg""" a = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ) return im @torch.no_grad() def __A ( __lowerCamelCase , __lowerCamelCase ) -> int: a = ViTConfig() a = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": a = True a = int(vit_name[-12:-10] ) a = int(vit_name[-9:-6] ) else: a = 1000 a = """huggingface/label-files""" a = """imagenet-1k-id2label.json""" a = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) a = {int(__lowerCamelCase ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} a = int(vit_name[-6:-4] ) a = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): a = 192 a = 768 a = 12 a = 3 elif vit_name[9:].startswith("""small""" ): a = 384 a = 1536 a = 12 a = 6 else: pass else: if vit_name[4:].startswith("""small""" ): a = 768 a = 2304 a = 8 a = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): a = 1024 a = 4096 a = 24 a = 16 elif vit_name[4:].startswith("""huge""" ): a = 1280 a = 5120 a = 32 a = 16 # load original model from timm a = timm.create_model(__lowerCamelCase , pretrained=__lowerCamelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys a = timm_model.state_dict() if base_model: remove_classification_head_(__lowerCamelCase ) a = create_rename_keys(__lowerCamelCase , __lowerCamelCase ) for src, dest in rename_keys: rename_key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) read_in_q_k_v(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # load HuggingFace model if vit_name[-5:] == "in21k": a = ViTModel(__lowerCamelCase ).eval() else: a = ViTForImageClassification(__lowerCamelCase ).eval() model.load_state_dict(__lowerCamelCase ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: a = DeiTImageProcessor(size=config.image_size ) else: a = ViTImageProcessor(size=config.image_size ) a = image_processor(images=prepare_img() , return_tensors="""pt""" ) a = encoding["""pixel_values"""] a = model(__lowerCamelCase ) if base_model: a = timm_model.forward_features(__lowerCamelCase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__lowerCamelCase , outputs.pooler_output , atol=1E-3 ) else: a = timm_model(__lowerCamelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__lowerCamelCase , outputs.logits , atol=1E-3 ) Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase ) print(f'Saving model {vit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__lowerCamelCase ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": __UpperCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_patch16_224", type=str, help="Name of the ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) __UpperCamelCase : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
347
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : Optional[int] = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
1