code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from math import factorial A_ = {str(d): factorial(d) for d in range(10)} def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , snake_case__ ) if sum_of_digit_factorial(snake_case__ ) == i ) if __name__ == "__main__": print(F'''{solution() = }''')
64
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str]=False ): """simple docstring""" _snake_case : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"module.blocks.{i}.norm1.weight", F"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((F"module.blocks.{i}.norm1.bias", F"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (F"module.blocks.{i}.attn.proj.weight", F"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.attn.proj.bias", F"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((F"module.blocks.{i}.norm2.weight", F"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((F"module.blocks.{i}.norm2.bias", F"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.weight", F"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.bias", F"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.weight", F"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.bias", F"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _snake_case : Any = [(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 UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : Dict , snake_case__ : List[str]=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _snake_case : List[Any] = """""" else: _snake_case : List[Any] = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.weight" ) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Optional[Any] = in_proj_weight[ : config.hidden_size, : ] _snake_case : Union[str, Any] = in_proj_bias[: config.hidden_size] _snake_case : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] _snake_case : List[str] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Tuple = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" _snake_case : List[str] = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : int ): """simple docstring""" _snake_case : Optional[Any] = dct.pop(snake_case__ ) _snake_case : Union[str, Any] = val def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : str ): """simple docstring""" _snake_case : str = ViTMSNConfig() _snake_case : Any = 10_00 _snake_case : Tuple = """datasets/huggingface/label-files""" _snake_case : Dict = """imagenet-1k-id2label.json""" _snake_case : int = json.load(open(hf_hub_download(snake_case__ , snake_case__ ) , """r""" ) ) _snake_case : Any = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[Any] = idalabel _snake_case : str = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: _snake_case : Tuple = 3_84 _snake_case : Dict = 15_36 _snake_case : Tuple = 6 elif "l16" in checkpoint_url: _snake_case : Any = 10_24 _snake_case : int = 40_96 _snake_case : str = 24 _snake_case : Optional[int] = 16 _snake_case : List[Any] = 0.1 elif "b4" in checkpoint_url: _snake_case : Tuple = 4 elif "l7" in checkpoint_url: _snake_case : int = 7 _snake_case : Dict = 10_24 _snake_case : Optional[Any] = 40_96 _snake_case : Any = 24 _snake_case : Union[str, Any] = 16 _snake_case : Optional[int] = 0.1 _snake_case : int = ViTMSNModel(snake_case__ ) _snake_case : Optional[int] = torch.hub.load_state_dict_from_url(snake_case__ , map_location="""cpu""" )["""target_encoder"""] _snake_case : List[str] = ViTImageProcessor(size=config.image_size ) remove_projection_head(snake_case__ ) _snake_case : List[str] = create_rename_keys(snake_case__ , base_model=snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_q_k_v(snake_case__ , snake_case__ , base_model=snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() _snake_case : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) _snake_case : str = ViTImageProcessor( size=config.image_size , image_mean=snake_case__ , image_std=snake_case__ ) _snake_case : Any = image_processor(images=snake_case__ , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) _snake_case : int = model(**snake_case__ ) _snake_case : List[Any] = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: _snake_case : Optional[Any] = torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] ) elif "b16" in checkpoint_url: _snake_case : str = torch.tensor([[14.28_89, -18.90_45, 11.72_81]] ) elif "l16" in checkpoint_url: _snake_case : Optional[int] = torch.tensor([[41.50_28, -22.86_81, 45.64_75]] ) elif "b4" in checkpoint_url: _snake_case : List[Any] = torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] ) else: _snake_case : Optional[int] = torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , snake_case__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A_ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
64
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available A_ = { '''configuration_audio_spectrogram_transformer''': [ '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ASTConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ASTForAudioClassification''', '''ASTModel''', '''ASTPreTrainedModel''', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''ASTFeatureExtractor'''] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str ): """simple docstring""" _snake_case : Optional[Any] = list(snake_case__ ) _snake_case : List[Any] = list(snake_case__ ) _snake_case : List[Any] = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count += 1 _snake_case : Any = """_""" if count > 1: return False else: return "".join(snake_case__ ) def UpperCAmelCase__ (snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [] while True: _snake_case : Union[str, Any] = ["""$"""] * len(snake_case__ ) _snake_case : int = [] for i in range(len(snake_case__ ) ): for j in range(i + 1 , len(snake_case__ ) ): _snake_case : List[Any] = compare_string(binary[i] , binary[j] ) if k is False: _snake_case : Dict = """*""" _snake_case : List[Any] = """*""" temp.append("""X""" ) for i in range(len(snake_case__ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case__ ) == 0: return pi _snake_case : Optional[int] = list(set(snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Sequence[float] ): """simple docstring""" _snake_case : Optional[int] = [] for minterm in minterms: _snake_case : Any = """""" for _ in range(snake_case__ ): _snake_case : Optional[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case__ ) return temp def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : int ): """simple docstring""" _snake_case : Dict = list(snake_case__ ) _snake_case : List[str] = list(snake_case__ ) _snake_case : Tuple = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCAmelCase__ (snake_case__ : list[list[int]] , snake_case__ : list[str] ): """simple docstring""" _snake_case : Any = [] _snake_case : Union[str, Any] = [0] * len(snake_case__ ) for i in range(len(chart[0] ) ): _snake_case : Tuple = 0 _snake_case : str = -1 for j in range(len(snake_case__ ) ): if chart[j][i] == 1: count += 1 _snake_case : Union[str, Any] = j if count == 1: _snake_case : Union[str, Any] = 1 for i in range(len(snake_case__ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case__ ) ): _snake_case : List[Any] = 0 temp.append(prime_implicants[i] ) while True: _snake_case : Optional[int] = 0 _snake_case : str = -1 _snake_case : Any = 0 for i in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _snake_case : Dict = count_n _snake_case : Dict = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case__ ) ): _snake_case : Optional[Any] = 0 def UpperCAmelCase__ (snake_case__ : list[str] , snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [[0 for x in range(len(snake_case__ ) )] for x in range(len(snake_case__ ) )] for i in range(len(snake_case__ ) ): _snake_case : Any = prime_implicants[i].count("""_""" ) for j in range(len(snake_case__ ) ): if is_for_table(prime_implicants[i] , binary[j] , snake_case__ ): _snake_case : Tuple = 1 return chart def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = int(input("""Enter the no. of variables\n""" ) ) _snake_case : List[str] = [ float(snake_case__ ) for x in input( """Enter the decimal representation of Minterms 'Spaces Separated'\n""" ).split() ] _snake_case : List[str] = decimal_to_binary(snake_case__ , snake_case__ ) _snake_case : str = check(snake_case__ ) print("""Prime Implicants are:""" ) print(snake_case__ ) _snake_case : int = prime_implicant_chart(snake_case__ , snake_case__ ) _snake_case : str = selection(snake_case__ , snake_case__ ) print("""Essential Prime Implicants are:""" ) print(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
64
1
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging A_ = logging.get_logger(__name__) class lowercase( __a ): '''simple docstring''' lowercase__ = "linear" lowercase__ = "cosine" lowercase__ = "cosine_with_restarts" lowercase__ = "polynomial" lowercase__ = "constant" lowercase__ = "constant_with_warmup" lowercase__ = "piecewise_constant" def UpperCAmelCase__ (snake_case__ : Optimizer , snake_case__ : int = -1 ): """simple docstring""" return LambdaLR(snake_case__ , lambda snake_case__ : 1 , last_epoch=snake_case__ ) def UpperCAmelCase__ (snake_case__ : Optimizer , snake_case__ : int , snake_case__ : int = -1 ): """simple docstring""" def lr_lambda(snake_case__ : int ): if current_step < num_warmup_steps: return float(snake_case__ ) / float(max(1.0 , snake_case__ ) ) return 1.0 return LambdaLR(snake_case__ , snake_case__ , last_epoch=snake_case__ ) def UpperCAmelCase__ (snake_case__ : Optimizer , snake_case__ : str , snake_case__ : int = -1 ): """simple docstring""" _snake_case : str = {} _snake_case : int = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: _snake_case , _snake_case : Any = rule_str.split(""":""" ) _snake_case : Optional[int] = int(snake_case__ ) _snake_case : str = float(snake_case__ ) _snake_case : Optional[int] = value _snake_case : Optional[Any] = float(rule_list[-1] ) def create_rules_function(snake_case__ : Optional[Any] , snake_case__ : str ): def rule_func(snake_case__ : int ) -> float: _snake_case : Optional[int] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(snake_case__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func _snake_case : List[str] = create_rules_function(snake_case__ , snake_case__ ) return LambdaLR(snake_case__ , snake_case__ , last_epoch=snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] , snake_case__ : Optional[Any] , snake_case__ : List[str] , snake_case__ : Optional[Any]=-1 ): """simple docstring""" def lr_lambda(snake_case__ : int ): if current_step < num_warmup_steps: return float(snake_case__ ) / float(max(1 , snake_case__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : Optimizer , snake_case__ : int , snake_case__ : int , snake_case__ : float = 0.5 , snake_case__ : int = -1 ): """simple docstring""" def lr_lambda(snake_case__ : Dict ): if current_step < num_warmup_steps: return float(snake_case__ ) / float(max(1 , snake_case__ ) ) _snake_case : List[Any] = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(snake_case__ ) * 2.0 * progress )) ) return LambdaLR(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : Optimizer , snake_case__ : int , snake_case__ : int , snake_case__ : int = 1 , snake_case__ : int = -1 ): """simple docstring""" def lr_lambda(snake_case__ : Dict ): if current_step < num_warmup_steps: return float(snake_case__ ) / float(max(1 , snake_case__ ) ) _snake_case : str = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(snake_case__ ) * progress) % 1.0) )) ) return LambdaLR(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : List[Any] , snake_case__ : List[Any] , snake_case__ : int=1e-7 , snake_case__ : Optional[Any]=1.0 , snake_case__ : Any=-1 ): """simple docstring""" _snake_case : str = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F"lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})" ) def lr_lambda(snake_case__ : int ): if current_step < num_warmup_steps: return float(snake_case__ ) / float(max(1 , snake_case__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: _snake_case : Tuple = lr_init - lr_end _snake_case : List[str] = num_training_steps - num_warmup_steps _snake_case : Any = 1 - (current_step - num_warmup_steps) / decay_steps _snake_case : List[Any] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(snake_case__ , snake_case__ , snake_case__ ) A_ = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def UpperCAmelCase__ (snake_case__ : Union[str, SchedulerType] , snake_case__ : Optimizer , snake_case__ : Optional[str] = None , snake_case__ : Optional[int] = None , snake_case__ : Optional[int] = None , snake_case__ : int = 1 , snake_case__ : float = 1.0 , snake_case__ : int = -1 , ): """simple docstring""" _snake_case : List[Any] = SchedulerType(snake_case__ ) _snake_case : Optional[Any] = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(snake_case__ , last_epoch=snake_case__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(snake_case__ , step_rules=snake_case__ , last_epoch=snake_case__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F"{name} requires `num_warmup_steps`, please provide that argument." ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(snake_case__ , num_warmup_steps=snake_case__ , last_epoch=snake_case__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F"{name} requires `num_training_steps`, please provide that argument." ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( snake_case__ , num_warmup_steps=snake_case__ , num_training_steps=snake_case__ , num_cycles=snake_case__ , last_epoch=snake_case__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( snake_case__ , num_warmup_steps=snake_case__ , num_training_steps=snake_case__ , power=snake_case__ , last_epoch=snake_case__ , ) return schedule_func( snake_case__ , num_warmup_steps=snake_case__ , num_training_steps=snake_case__ , last_epoch=snake_case__ )
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" stooge(snake_case__ , 0 , len(snake_case__ ) - 1 ) return arr def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int ): """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _snake_case , _snake_case : Tuple = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _snake_case : Dict = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case__ , i + t , (snake_case__) ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(stooge_sort(unsorted))
64
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ = {'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''YolosFeatureExtractor'''] A_ = ['''YolosImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''YolosForObjectDetection''', '''YolosModel''', '''YolosPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase( metaclass=__a ): '''simple docstring''' lowercase__ = ["note_seq"] def __init__( self: Dict, *a_: Union[str, Any], **a_: List[str] ): '''simple docstring''' requires_backends(self, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Optional[int], *a_: Any, **a_: Optional[Any] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Tuple, *a_: Optional[Any], **a_: List[str] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] )
64
1
"""simple docstring""" from typing import Any import numpy as np def UpperCAmelCase__ (snake_case__ : np.ndarray ): """simple docstring""" return np.array_equal(snake_case__ , matrix.conjugate().T ) def UpperCAmelCase__ (snake_case__ : np.ndarray , snake_case__ : np.ndarray ): """simple docstring""" _snake_case : Optional[int] = v.conjugate().T _snake_case : List[Any] = v_star.dot(snake_case__ ) assert isinstance(snake_case__ , np.ndarray ) return (v_star_dot.dot(snake_case__ )) / (v_star.dot(snake_case__ )) def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) _snake_case : int = np.array([[1], [2], [3]] ) assert is_hermitian(snake_case__ ), F"{a} is not hermitian." print(rayleigh_quotient(snake_case__ , snake_case__ ) ) _snake_case : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(snake_case__ ), F"{a} is not hermitian." assert rayleigh_quotient(snake_case__ , snake_case__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
64
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : int = data _snake_case : Dict = [0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def UpperCamelCase_ ( a_: Optional[Any], a_: Dict ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xffffffff def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) _snake_case : Optional[int] = self.data + padding + struct.pack(""">Q""", 8 * len(self.data ) ) return padded_data def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def UpperCamelCase_ ( self: Optional[Any], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = list(struct.unpack(""">16L""", a_ ) ) + [0] * 64 for i in range(16, 80 ): _snake_case : List[Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = self.padding() _snake_case : str = self.split_blocks() for block in self.blocks: _snake_case : Any = self.expand_block(a_ ) _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = self.h for i in range(0, 80 ): if 0 <= i < 20: _snake_case : int = (b & c) | ((~b) & d) _snake_case : str = 0X5a827999 elif 20 <= i < 40: _snake_case : Optional[int] = b ^ c ^ d _snake_case : str = 0X6ed9eba1 elif 40 <= i < 60: _snake_case : List[Any] = (b & c) | (b & d) | (c & d) _snake_case : List[Any] = 0X8f1bbcdc elif 60 <= i < 80: _snake_case : List[Any] = b ^ c ^ d _snake_case : int = 0Xca62c1d6 _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = ( self.rotate(a_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(a_, 30 ), c, d, ) _snake_case : Union[str, Any] = ( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = B"""Test String""" assert SHAaHash(snake_case__ ).final_hash() == hashlib.shaa(snake_case__ ).hexdigest() # noqa: S324 def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _snake_case : Union[str, Any] = parser.parse_args() _snake_case : List[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _snake_case : str = f.read() else: _snake_case : int = bytes(snake_case__ , """utf-8""" ) print(SHAaHash(snake_case__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
64
1
"""simple docstring""" from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase( __a ): '''simple docstring''' lowercase__ = "new-model" if is_tf_available(): class lowercase( __a ): '''simple docstring''' lowercase__ = NewModelConfig @require_tf class lowercase( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Dict = """bert-base-cased""" _snake_case : Tuple = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : int = TFAutoModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Optional[int] = """bert-base-cased""" _snake_case : Any = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : Tuple = TFAutoModelForPreTraining.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : str = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : Optional[Any] = TFAutoModelForCausalLM.from_pretrained(a_ ) _snake_case , _snake_case : Dict = TFAutoModelForCausalLM.from_pretrained(a_, output_loading_info=a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow def UpperCamelCase_ ( self: Dict ): '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : Tuple = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : Union[str, Any] = TFAutoModelWithLMHead.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow def UpperCamelCase_ ( self: Dict ): '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : int = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(a_ ) _snake_case , _snake_case : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(a_, output_loading_info=a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow def UpperCamelCase_ ( self: Dict ): '''simple docstring''' for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : int = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(a_ ) _snake_case , _snake_case : List[str] = TFAutoModelForSeqaSeqLM.from_pretrained(a_, output_loading_info=a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow def UpperCamelCase_ ( self: Dict ): '''simple docstring''' for model_name in ["bert-base-uncased"]: _snake_case : Dict = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : Optional[Any] = TFAutoModelForSequenceClassification.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' for model_name in ["bert-base-uncased"]: _snake_case : Optional[int] = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : List[Any] = TFAutoModelForQuestionAnswering.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) @slow @require_tensorflow_probability def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: _snake_case : int = AutoConfig.from_pretrained(a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) _snake_case : Dict = TFAutoModelForTableQuestionAnswering.from_pretrained(a_ ) _snake_case , _snake_case : List[Any] = TFAutoModelForTableQuestionAnswering.from_pretrained( a_, output_loading_info=a_ ) self.assertIsNotNone(a_ ) self.assertIsInstance(a_, a_ ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : Tuple = TFAutoModelWithLMHead.from_pretrained(a_ ) self.assertIsInstance(a_, a_ ) self.assertEqual(model.num_parameters(), 14_410 ) self.assertEqual(model.num_parameters(only_trainable=a_ ), 14_410 ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : List[Any] = TFAutoModelWithLMHead.from_pretrained(a_ ) self.assertIsInstance(a_, a_ ) self.assertEqual(model.num_parameters(), 14_410 ) self.assertEqual(model.num_parameters(only_trainable=a_ ), 14_410 ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : Any = TFAutoModel.from_pretrained("""sgugger/funnel-random-tiny""" ) self.assertIsInstance(a_, a_ ) _snake_case : Any = copy.deepcopy(model.config ) _snake_case : Dict = ["""FunnelBaseModel"""] _snake_case : Optional[Any] = TFAutoModel.from_config(a_ ) self.assertIsInstance(a_, a_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(a_ ) _snake_case : List[str] = TFAutoModel.from_pretrained(a_ ) self.assertIsInstance(a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' try: AutoConfig.register("""new-model""", a_ ) _snake_case : Union[str, Any] = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(a_ ): auto_class.register(a_, a_ ) auto_class.register(a_, a_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(a_ ): auto_class.register(a_, a_ ) # Now that the config is registered, it can be used as any other config with the auto-API _snake_case : List[Any] = BertModelTester(self ).get_config() _snake_case : Optional[int] = NewModelConfig(**tiny_config.to_dict() ) _snake_case : List[str] = auto_class.from_config(a_ ) self.assertIsInstance(a_, a_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(a_ ) _snake_case : Optional[Any] = auto_class.from_pretrained(a_ ) self.assertIsInstance(a_, a_ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def UpperCamelCase_ ( self: Dict ): '''simple docstring''' with self.assertRaisesRegex( a_, """bert-base is not a local folder and is not a valid model identifier""" ): _snake_case : List[Any] = TFAutoModel.from_pretrained("""bert-base""" ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' with self.assertRaisesRegex( a_, r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): _snake_case : int = TFAutoModel.from_pretrained(a_, revision="""aaaaaa""" ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' with self.assertRaisesRegex( a_, """hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin""", ): _snake_case : Optional[int] = TFAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' with self.assertRaisesRegex(a_, """Use `from_pt=True` to load this model""" ): _snake_case : Optional[int] = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Any = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: _snake_case : Any = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count, 0 ) self.assertEqual(counter.head_request_count, 1 ) self.assertEqual(counter.other_request_count, 0 ) # With a sharded checkpoint _snake_case : Dict = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) with RequestCounter() as counter: _snake_case : Optional[Any] = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) self.assertEqual(counter.get_request_count, 0 ) self.assertEqual(counter.head_request_count, 1 ) self.assertEqual(counter.other_request_count, 0 )
64
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings A_ = r''' [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: title_sep (`str`, *optional*, defaults to `" / "`): Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`]. doc_sep (`str`, *optional*, defaults to `" // "`): Separator inserted between the text of the retrieved document and the original input when calling [`RagRetriever`]. n_docs (`int`, *optional*, defaults to 5): Number of documents to retrieve. max_combined_length (`int`, *optional*, defaults to 300): Max length of contextualized input returned by [`~RagRetriever.__call__`]. retrieval_vector_size (`int`, *optional*, defaults to 768): Dimensionality of the document embeddings indexed by [`RagRetriever`]. retrieval_batch_size (`int`, *optional*, defaults to 8): Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated [`RagRetriever`]. dataset (`str`, *optional*, defaults to `"wiki_dpr"`): A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids using `datasets.list_datasets()`). dataset_split (`str`, *optional*, defaults to `"train"`) Which split of the `dataset` to load. index_name (`str`, *optional*, defaults to `"compressed"`) The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and `"compressed"`. index_path (`str`, *optional*) The path to the serialized faiss index on disk. passages_path (`str`, *optional*): A path to text passages compatible with the faiss index. Required if using [`~models.rag.retrieval_rag.LegacyIndex`] use_dummy_dataset (`bool`, *optional*, defaults to `False`) Whether to load a "dummy" variant of the dataset specified by `dataset`. label_smoothing (`float`, *optional*, defaults to 0.0): Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed. do_marginalize (`bool`, *optional*, defaults to `False`): If `True`, the logits are marginalized over all documents by making use of `torch.nn.functional.log_softmax`. reduce_loss (`bool`, *optional*, defaults to `False`): Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation. do_deduplication (`bool`, *optional*, defaults to `True`): Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to `False` if used while training with distributed backend. exclude_bos_score (`bool`, *optional*, defaults to `False`): Whether or not to disregard the BOS token when computing the loss. output_retrieved(`bool`, *optional*, defaults to `False`): If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and `context_attention_mask` are returned. See returned tensors for more detail. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). forced_eos_token_id (`int`, *optional*): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`. ''' @add_start_docstrings(__a ) class lowercase( __a ): '''simple docstring''' lowercase__ = "rag" lowercase__ = True def __init__( self: Union[str, Any], a_: int=None, a_: Tuple=True, a_: Optional[int]=None, a_: List[str]=None, a_: int=None, a_: Optional[Any]=None, a_: List[str]=None, a_: Optional[Any]=" / ", a_: Tuple=" // ", a_: List[Any]=5, a_: Dict=300, a_: Tuple=768, a_: Optional[Any]=8, a_: int="wiki_dpr", a_: Any="train", a_: Optional[int]="compressed", a_: Optional[int]=None, a_: List[Any]=None, a_: Optional[Any]=False, a_: str=False, a_: Dict=0.0, a_: Union[str, Any]=True, a_: Union[str, Any]=False, a_: str=False, a_: List[str]=False, a_: Union[str, Any]=True, a_: Any=None, **a_: List[Any], ): '''simple docstring''' super().__init__( bos_token_id=a_, pad_token_id=a_, eos_token_id=a_, decoder_start_token_id=a_, forced_eos_token_id=a_, is_encoder_decoder=a_, prefix=a_, vocab_size=a_, **a_, ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _snake_case : Union[str, Any] = kwargs.pop("""question_encoder""" ) _snake_case : List[str] = question_encoder_config.pop("""model_type""" ) _snake_case : Union[str, Any] = kwargs.pop("""generator""" ) _snake_case : Any = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig _snake_case : Union[str, Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Optional[Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Any = reduce_loss _snake_case : Optional[int] = label_smoothing _snake_case : Dict = exclude_bos_score _snake_case : int = do_marginalize _snake_case : Optional[Any] = title_sep _snake_case : Any = doc_sep _snake_case : List[str] = n_docs _snake_case : Tuple = max_combined_length _snake_case : Optional[Any] = dataset _snake_case : Union[str, Any] = dataset_split _snake_case : Tuple = index_name _snake_case : Any = retrieval_vector_size _snake_case : Union[str, Any] = retrieval_batch_size _snake_case : str = passages_path _snake_case : Tuple = index_path _snake_case : List[Any] = use_dummy_dataset _snake_case : Optional[Any] = output_retrieved _snake_case : Tuple = do_deduplication _snake_case : Union[str, Any] = use_cache if self.forced_eos_token_id is None: _snake_case : Dict = getattr(self.generator, """forced_eos_token_id""", a_ ) @classmethod def UpperCamelCase_ ( cls: Any, a_: PretrainedConfig, a_: PretrainedConfig, **a_: Optional[Any] ): '''simple docstring''' return cls(question_encoder=question_encoder_config.to_dict(), generator=generator_config.to_dict(), **a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Optional[int] = copy.deepcopy(self.__dict__ ) _snake_case : List[str] = self.question_encoder.to_dict() _snake_case : Tuple = self.generator.to_dict() _snake_case : Dict = self.__class__.model_type return output
64
1
"""simple docstring""" 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 MobileViTImageProcessor class lowercase( unittest.TestCase ): '''simple docstring''' def __init__( self: Dict, a_: Dict, a_: Union[str, Any]=7, a_: Tuple=3, a_: List[str]=18, a_: Optional[int]=30, a_: Optional[Any]=400, a_: str=True, a_: List[str]=None, a_: Union[str, Any]=True, a_: Union[str, Any]=None, a_: str=True, ): '''simple docstring''' _snake_case : List[Any] = size if size is not None else {"""shortest_edge""": 20} _snake_case : Tuple = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} _snake_case : Optional[int] = parent _snake_case : Dict = batch_size _snake_case : Dict = num_channels _snake_case : List[Any] = image_size _snake_case : Tuple = min_resolution _snake_case : List[Any] = max_resolution _snake_case : Optional[Any] = do_resize _snake_case : List[str] = size _snake_case : int = do_center_crop _snake_case : str = crop_size _snake_case : Dict = do_flip_channel_order def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = MobileViTImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Tuple = MobileViTImageProcessingTester(self ) @property def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_, """do_resize""" ) ) self.assertTrue(hasattr(a_, """size""" ) ) self.assertTrue(hasattr(a_, """do_center_crop""" ) ) self.assertTrue(hasattr(a_, """center_crop""" ) ) self.assertTrue(hasattr(a_, """do_flip_channel_order""" ) ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Dict = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {"""shortest_edge""": 20} ) self.assertEqual(image_processor.crop_size, {"""height""": 18, """width""": 18} ) _snake_case : Tuple = self.image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84 ) self.assertEqual(image_processor.size, {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size, {"""height""": 84, """width""": 84} ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' _snake_case : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _snake_case : List[Any] = prepare_image_inputs(self.image_processor_tester, equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_, Image.Image ) # Test not batched input _snake_case : str = image_processing(image_inputs[0], return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ), ) # Test batched _snake_case : Union[str, Any] = image_processing(a_, return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ), ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' _snake_case : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _snake_case : Any = prepare_image_inputs(self.image_processor_tester, equal_resolution=a_, numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_, np.ndarray ) # Test not batched input _snake_case : Tuple = image_processing(image_inputs[0], return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ), ) # Test batched _snake_case : str = image_processing(a_, return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ), ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _snake_case : Dict = prepare_image_inputs(self.image_processor_tester, equal_resolution=a_, torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_, torch.Tensor ) # Test not batched input _snake_case : str = image_processing(image_inputs[0], return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ), ) # Test batched _snake_case : Optional[Any] = image_processing(a_, return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ), )
64
"""simple docstring""" import os from typing import Dict, List, Tuple, TypeVar, Union A_ = TypeVar('''T''') A_ = Union[List[T], Tuple[T, ...]] A_ = Union[T, List[T], Dict[str, T]] A_ = Union[str, bytes, os.PathLike]
64
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: A_ = None A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''', '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model''' ), }, '''tokenizer_file''': { '''google/bigbird-roberta-base''': ( '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json''' ), '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json''' ), }, } A_ = { '''google/bigbird-roberta-base''': 40_96, '''google/bigbird-roberta-large''': 40_96, '''google/bigbird-base-trivia-itc''': 40_96, } A_ = '''▁''' class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = BigBirdTokenizer lowercase__ = ["input_ids", "attention_mask"] lowercase__ = [] def __init__( self: int, a_: Union[str, Any]=None, a_: Union[str, Any]=None, a_: Any="<unk>", a_: Tuple="<s>", a_: Tuple="</s>", a_: Dict="<pad>", a_: int="[SEP]", a_: Any="[MASK]", a_: str="[CLS]", **a_: Optional[Any], ): '''simple docstring''' _snake_case : Dict = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else bos_token _snake_case : Union[str, Any] = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else eos_token _snake_case : str = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else unk_token _snake_case : Any = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else pad_token _snake_case : Union[str, Any] = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else cls_token _snake_case : Optional[Any] = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it _snake_case : Optional[int] = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else mask_token super().__init__( a_, tokenizer_file=a_, bos_token=a_, eos_token=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, **a_, ) _snake_case : Any = vocab_file _snake_case : Optional[int] = False if not self.vocab_file else True def UpperCamelCase_ ( self: int, a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Optional[int] = [self.sep_token_id] _snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self: Optional[int], a_: List[int], a_: Optional[List[int]] = None, a_: bool = False ): '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(a_ )) + [1] return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1] def UpperCamelCase_ ( self: int, a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : List[str] = [self.sep_token_id] _snake_case : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: List[Any], a_: str, a_: 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(a_ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _snake_case : int = os.path.join( a_, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file, a_ ) return (out_vocab_file,)
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] _snake_case : List[Any] = [] def generate(snake_case__ : int , snake_case__ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even _snake_case , _snake_case : Optional[Any] = arr[k - 1], arr[i] else: # k is odd _snake_case , _snake_case : List[str] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
64
1
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class lowercase( __a ): '''simple docstring''' lowercase__ = 42 lowercase__ = None def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[Any]=0.9_99 , snake_case__ : Dict="cosine" , ): """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Dict ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.exp(t * -12.0 ) else: raise ValueError(F"Unsupported alpha_tranform_type: {alpha_transform_type}" ) _snake_case : int = [] for i in range(snake_case__ ): _snake_case : Tuple = i / num_diffusion_timesteps _snake_case : Union[str, Any] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowercase( __a , __a ): '''simple docstring''' @register_to_config def __init__( self: List[str], a_: int = 1_000, a_: str = "fixed_small_log", a_: bool = True, a_: Optional[float] = 1.0, a_: str = "epsilon", a_: str = "squaredcos_cap_v2", ): '''simple docstring''' if beta_schedule != "squaredcos_cap_v2": raise ValueError("""UnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'""" ) _snake_case : Tuple = betas_for_alpha_bar(a_ ) _snake_case : List[str] = 1.0 - self.betas _snake_case : Optional[int] = torch.cumprod(self.alphas, dim=0 ) _snake_case : Tuple = torch.tensor(1.0 ) # standard deviation of the initial noise distribution _snake_case : Optional[Any] = 1.0 # setable values _snake_case : str = None _snake_case : Tuple = torch.from_numpy(np.arange(0, a_ )[::-1].copy() ) _snake_case : int = variance_type def UpperCamelCase_ ( self: Dict, a_: torch.FloatTensor, a_: Optional[int] = None ): '''simple docstring''' return sample def UpperCamelCase_ ( self: Any, a_: int, a_: Union[str, torch.device] = None ): '''simple docstring''' _snake_case : List[Any] = num_inference_steps _snake_case : Any = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) _snake_case : Optional[int] = (np.arange(0, a_ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) _snake_case : Optional[Any] = torch.from_numpy(a_ ).to(a_ ) def UpperCamelCase_ ( self: List[Any], a_: Tuple, a_: Dict=None, a_: Union[str, Any]=None, a_: Tuple=None ): '''simple docstring''' if prev_timestep is None: _snake_case : Optional[Any] = t - 1 _snake_case : Dict = self.alphas_cumprod[t] _snake_case : List[Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _snake_case : List[str] = 1 - alpha_prod_t _snake_case : List[Any] = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _snake_case : int = self.betas[t] else: _snake_case : Union[str, Any] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _snake_case : int = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: _snake_case : Any = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": _snake_case : Optional[int] = torch.log(torch.clamp(a_, min=1E-20 ) ) _snake_case : int = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler _snake_case : Optional[Any] = variance.log() _snake_case : List[str] = beta.log() _snake_case : Optional[int] = (predicted_variance + 1) / 2 _snake_case : Dict = frac * max_log + (1 - frac) * min_log return variance def UpperCamelCase_ ( self: Optional[Any], a_: torch.FloatTensor, a_: int, a_: torch.FloatTensor, a_: Optional[int] = None, a_: Tuple=None, a_: bool = True, ): '''simple docstring''' _snake_case : List[Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": _snake_case , _snake_case : str = torch.split(a_, sample.shape[1], dim=1 ) else: _snake_case : Dict = None # 1. compute alphas, betas if prev_timestep is None: _snake_case : Optional[Any] = t - 1 _snake_case : Optional[int] = self.alphas_cumprod[t] _snake_case : Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _snake_case : Optional[Any] = 1 - alpha_prod_t _snake_case : int = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _snake_case : str = self.betas[t] _snake_case : int = self.alphas[t] else: _snake_case : Dict = 1 - alpha_prod_t / alpha_prod_t_prev _snake_case : str = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _snake_case : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _snake_case : Tuple = model_output else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`" """ for the UnCLIPScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: _snake_case : int = torch.clamp( a_, -self.config.clip_sample_range, self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _snake_case : List[Any] = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t _snake_case : Any = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _snake_case : Dict = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _snake_case : Any = 0 if t > 0: _snake_case : str = randn_tensor( model_output.shape, dtype=model_output.dtype, generator=a_, device=model_output.device ) _snake_case : Union[str, Any] = self._get_variance( a_, predicted_variance=a_, prev_timestep=a_, ) if self.variance_type == "fixed_small_log": _snake_case : Tuple = variance elif self.variance_type == "learned_range": _snake_case : int = (0.5 * variance).exp() else: raise ValueError( f"variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`" """ for the UnCLIPScheduler.""" ) _snake_case : List[Any] = variance * variance_noise _snake_case : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=a_, pred_original_sample=a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: torch.FloatTensor, a_: torch.FloatTensor, a_: torch.IntTensor, ): '''simple docstring''' _snake_case : List[Any] = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype ) _snake_case : str = timesteps.to(original_samples.device ) _snake_case : Union[str, Any] = alphas_cumprod[timesteps] ** 0.5 _snake_case : List[str] = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): _snake_case : Optional[Any] = sqrt_alpha_prod.unsqueeze(-1 ) _snake_case : Tuple = (1 - alphas_cumprod[timesteps]) ** 0.5 _snake_case : Optional[Any] = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): _snake_case : str = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) _snake_case : Any = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
64
"""simple docstring""" from math import factorial A_ = {str(d): factorial(d) for d in range(10)} def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , snake_case__ ) if sum_of_digit_factorial(snake_case__ ) == i ) if __name__ == "__main__": print(F'''{solution() = }''')
64
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''sentencepiece.bpe.model'''} A_ = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', } } A_ = { '''camembert-base''': 5_12, } A_ = '''▁''' class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] def __init__( self: Union[str, Any], a_: List[str], a_: List[str]="<s>", a_: Union[str, Any]="</s>", a_: List[str]="</s>", a_: Any="<s>", a_: str="<unk>", a_: Optional[Any]="<pad>", a_: List[Any]="<mask>", a_: Optional[Any]=["<s>NOTUSED", "</s>NOTUSED"], a_: Optional[Dict[str, Any]] = None, **a_: List[str], ): '''simple docstring''' _snake_case : List[str] = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else mask_token _snake_case : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=a_, eos_token=a_, unk_token=a_, sep_token=a_, cls_token=a_, pad_token=a_, mask_token=a_, additional_special_tokens=a_, sp_model_kwargs=self.sp_model_kwargs, **a_, ) _snake_case : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(a_ ) ) _snake_case : List[str] = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> _snake_case : List[str] = {"""<s>NOTUSED""": 0, """<pad>""": 1, """</s>NOTUSED""": 2, """<unk>""": 3} _snake_case : List[Any] = len(self.fairseq_tokens_to_ids ) _snake_case : List[str] = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) _snake_case : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self: Optional[Any], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _snake_case : int = [self.cls_token_id] _snake_case : Any = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self: Optional[int], a_: List[int], a_: Optional[List[int]] = None, a_: bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_, token_ids_a=a_, already_has_special_tokens=a_ ) if token_ids_a is None: return [1] + ([0] * len(a_ )) + [1] return [1] + ([0] * len(a_ )) + [1, 1] + ([0] * len(a_ )) + [1] def UpperCamelCase_ ( self: Optional[Any], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : str = [self.sep_token_id] _snake_case : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Tuple = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self: List[str], a_: str ): '''simple docstring''' return self.sp_model.encode(a_, out_type=a_ ) def UpperCamelCase_ ( self: List[Any], a_: List[Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(a_ ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(a_ ) def UpperCamelCase_ ( self: Any, a_: Optional[int] ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self: List[str], a_: List[str] ): '''simple docstring''' _snake_case : Tuple = [] _snake_case : Optional[int] = """""" _snake_case : Optional[Any] = 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(a_ ) + token _snake_case : Tuple = True _snake_case : Any = [] else: current_sub_tokens.append(a_ ) _snake_case : Optional[int] = False out_string += self.sp_model.decode(a_ ) return out_string.strip() def __getstate__( self: Tuple ): '''simple docstring''' _snake_case : int = self.__dict__.copy() _snake_case : Optional[int] = None return state def __setstate__( self: int, a_: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = d # for backward compatibility if not hasattr(self, """sp_model_kwargs""" ): _snake_case : List[Any] = {} _snake_case : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self: str, a_: str, a_: Optional[str] = None ): '''simple docstring''' if not os.path.isdir(a_ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _snake_case : Optional[Any] = os.path.join( a_, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_, """wb""" ) as fi: _snake_case : Dict = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
64
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : int ): """simple docstring""" if len(snake_case__ ) < k or k < 0: raise ValueError("""Invalid Input""" ) _snake_case : Optional[int] = sum(array[:k] ) for i in range(len(snake_case__ ) - k ): _snake_case : Optional[Any] = current_sum - array[i] + array[i + k] _snake_case : List[str] = max(snake_case__ , snake_case__ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() A_ = [randint(-10_00, 10_00) for i in range(1_00)] A_ = randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
64
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''sentencepiece.bpe.model'''} A_ = { '''vocab_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model''' ), }, } A_ = { '''moussaKam/mbarthez''': 10_24, '''moussaKam/barthez''': 10_24, '''moussaKam/barthez-orangesum-title''': 10_24, } A_ = '''▁''' class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] def __init__( self: List[Any], a_: Tuple, a_: Optional[Any]="<s>", a_: Optional[int]="</s>", a_: Any="</s>", a_: Dict="<s>", a_: Tuple="<unk>", a_: Optional[Any]="<pad>", a_: str="<mask>", a_: Optional[Dict[str, Any]] = None, **a_: Union[str, Any], ): '''simple docstring''' _snake_case : int = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else mask_token _snake_case : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=a_, eos_token=a_, unk_token=a_, sep_token=a_, cls_token=a_, pad_token=a_, mask_token=a_, sp_model_kwargs=self.sp_model_kwargs, **a_, ) _snake_case : Any = vocab_file _snake_case : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(a_ ) ) _snake_case : Optional[Any] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} _snake_case : Union[str, Any] = len(self.sp_model ) - 1 _snake_case : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self: Optional[Any], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _snake_case : str = [self.cls_token_id] _snake_case : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self: List[Any], a_: List[int], a_: Optional[List[int]] = None, a_: bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_, token_ids_a=a_, already_has_special_tokens=a_ ) if token_ids_a is None: return [1] + ([0] * len(a_ )) + [1] return [1] + ([0] * len(a_ )) + [1, 1] + ([0] * len(a_ )) + [1] def UpperCamelCase_ ( self: str, a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self: int ): '''simple docstring''' return len(self.sp_model ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : str = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self: Dict, a_: str ): '''simple docstring''' return self.sp_model.encode(a_, out_type=a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Union[str, Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _snake_case : Optional[int] = self.sp_model.PieceToId(a_ ) return spm_id if spm_id else self.unk_token_id def UpperCamelCase_ ( self: Tuple, a_: Tuple ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(a_ ) def UpperCamelCase_ ( self: Optional[int], a_: int ): '''simple docstring''' _snake_case : List[Any] = [] _snake_case : Dict = """""" _snake_case : int = 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(a_ ) + token _snake_case : Optional[int] = True _snake_case : str = [] else: current_sub_tokens.append(a_ ) _snake_case : List[str] = False out_string += self.sp_model.decode(a_ ) return out_string.strip() def __getstate__( self: int ): '''simple docstring''' _snake_case : Optional[Any] = self.__dict__.copy() _snake_case : Optional[Any] = None return state def __setstate__( self: Optional[int], a_: Union[str, Any] ): '''simple docstring''' _snake_case : Optional[Any] = d # for backward compatibility if not hasattr(self, """sp_model_kwargs""" ): _snake_case : Tuple = {} _snake_case : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self: Optional[Any], a_: str, a_: Optional[str] = None ): '''simple docstring''' if not os.path.isdir(a_ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _snake_case : Union[str, Any] = os.path.join( a_, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_, """wb""" ) as fi: _snake_case : List[str] = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
64
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } A_ = { '''yjernite/retribert-base-uncased''': 5_12, } A_ = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = RetriBertTokenizer lowercase__ = ["input_ids", "attention_mask"] def __init__( self: int, a_: int=None, a_: Dict=None, a_: Any=True, a_: int="[UNK]", a_: Any="[SEP]", a_: List[Any]="[PAD]", a_: List[Any]="[CLS]", a_: str="[MASK]", a_: Dict=True, a_: Optional[int]=None, **a_: Tuple, ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Dict = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : List[Any] = do_lower_case _snake_case : List[str] = strip_accents _snake_case : Tuple = tokenize_chinese_chars _snake_case : Tuple = normalizer_class(**a_ ) _snake_case : List[str] = do_lower_case def UpperCamelCase_ ( self: Any, a_: str, a_: Optional[int]=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: List[str], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: Dict, a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : Union[str, Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
1
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs A_ = imread(r'''digital_image_processing/image_data/lena_small.jpg''') A_ = cvtColor(img, COLOR_BGR2GRAY) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Dict = cn.convert_to_negative(snake_case__ ) # assert negative_img array for at least one True assert negative_img.any() def UpperCAmelCase__ (): """simple docstring""" with Image.open("""digital_image_processing/image_data/lena_small.jpg""" ) as img: # Work around assertion for response assert str(cc.change_contrast(snake_case__ , 1_10 ) ).startswith( """<PIL.Image.Image image mode=RGB size=100x100 at""" ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Optional[int] = imread("""digital_image_processing/image_data/lena_small.jpg""" , 0 ) # assert ambiguous array for all == True assert canny_img.all() _snake_case : Optional[Any] = canny.canny(snake_case__ ) # assert canny array for at least one True assert canny_array.any() def UpperCAmelCase__ (): """simple docstring""" assert gg.gaussian_filter(snake_case__ , 5 , sigma=0.9 ).all() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) _snake_case : Optional[int] = conv.img_convolve(snake_case__ , snake_case__ ).astype(snake_case__ ) assert res.any() def UpperCAmelCase__ (): """simple docstring""" assert med.median_filter(snake_case__ , 3 ).any() def UpperCAmelCase__ (): """simple docstring""" _snake_case , _snake_case : int = sob.sobel_filter(snake_case__ ) assert grad.any() and theta.any() def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = sp.make_sepia(snake_case__ , 20 ) assert sepia.all() def UpperCAmelCase__ (snake_case__ : str = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" _snake_case : Any = bs.Burkes(imread(snake_case__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def UpperCAmelCase__ (snake_case__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" _snake_case : Optional[Any] = rs.NearestNeighbour(imread(snake_case__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Union[str, Any] = """digital_image_processing/image_data/lena.jpg""" # Reading the image and converting it to grayscale. _snake_case : List[Any] = imread(snake_case__ , 0 ) # Test for get_neighbors_pixel function() return not None _snake_case : str = 0 _snake_case : Union[str, Any] = 0 _snake_case : Optional[int] = image[x_coordinate][y_coordinate] _snake_case : str = lbp.get_neighbors_pixel( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image _snake_case : Tuple = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): _snake_case : Optional[int] = lbp.local_binary_value(snake_case__ , snake_case__ , snake_case__ ) assert lbp_image.any()
64
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CodeGenTokenizer lowercase__ = CodeGenTokenizerFast lowercase__ = True lowercase__ = {"add_prefix_space": True} lowercase__ = False def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _snake_case : Tuple = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] _snake_case : Tuple = dict(zip(a_, range(len(a_ ) ) ) ) _snake_case : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _snake_case : List[Any] = {"""unk_token""": """<unk>"""} _snake_case : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) _snake_case : Optional[Any] = 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(a_ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(a_ ) ) def UpperCamelCase_ ( self: Any, **a_: int ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Any, **a_: str ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Dict ): '''simple docstring''' _snake_case : Union[str, Any] = """lower newer""" _snake_case : Tuple = """lower newer""" return input_text, output_text def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) _snake_case : Optional[Any] = """lower newer""" _snake_case : Optional[int] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] _snake_case : int = tokenizer.tokenize(a_, add_prefix_space=a_ ) self.assertListEqual(a_, a_ ) _snake_case : str = tokens + [tokenizer.unk_token] _snake_case : Optional[int] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : int = self.get_tokenizer() _snake_case : int = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : Dict = """lower newer""" # Testing tokenization _snake_case : Dict = tokenizer.tokenize(a_, add_prefix_space=a_ ) _snake_case : List[str] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids without special tokens _snake_case : Optional[Any] = tokenizer.encode(a_, add_special_tokens=a_, add_prefix_space=a_ ) _snake_case : Tuple = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids with special tokens _snake_case : Tuple = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : int = tokenizer.encode(a_, add_prefix_space=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) # Testing the unknown token _snake_case : Tuple = tokens + [rust_tokenizer.unk_token] _snake_case : List[Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Dict, *a_: Dict, **a_: int ): '''simple docstring''' pass def UpperCamelCase_ ( self: int, a_: List[Any]=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : List[Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) # Simple input _snake_case : Any = """This is a simple input""" _snake_case : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Optional[int] = ("""This is a simple input""", """This is a pair""") _snake_case : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) # Pair input self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token="""<pad>""" ) # Simple input _snake_case : List[Any] = """This is a simple input""" _snake_case : int = ["""This is a simple input looooooooong""", """This is a simple input"""] _snake_case : Any = ("""This is a simple input""", """This is a pair""") _snake_case : str = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] _snake_case : str = tokenizer.pad_token_id _snake_case : Optional[int] = tokenizer(a_, padding="""max_length""", max_length=30, return_tensors="""np""" ) _snake_case : Dict = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) _snake_case : Tuple = tokenizer(*a_, padding="""max_length""", max_length=60, return_tensors="""np""" ) _snake_case : Optional[Any] = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Tuple = """$$$""" _snake_case : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=a_, add_bos_token=a_ ) _snake_case : str = """This is a simple input""" _snake_case : int = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Tuple = tokenizer(a_ ) _snake_case : Optional[Any] = tokenizer(a_ ) self.assertEqual(out_s.input_ids[0], a_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) _snake_case : Optional[int] = tokenizer.decode(out_s.input_ids ) _snake_case : int = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], a_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) _snake_case : Dict = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" _snake_case : Union[str, Any] = """\nif len_a > len_b: result = a\nelse: result = b""" _snake_case : Optional[Any] = tokenizer.encode(a_ ) _snake_case : Dict = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] _snake_case : Optional[Any] = tokenizer.decode(a_, truncate_before_pattern=a_ ) self.assertEqual(a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' pass
64
1
"""simple docstring""" from typing import List from .keymap import KEYMAP, get_character def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" def decorator(snake_case__ : Optional[int] ): _snake_case : List[Any] = getattr(snake_case__ , """handle_key""" , [] ) handle += [key] setattr(snake_case__ , """handle_key""" , snake_case__ ) return func return decorator def UpperCAmelCase__ (*snake_case__ : List[str] ): """simple docstring""" def decorator(snake_case__ : List[Any] ): _snake_case : Optional[Any] = getattr(snake_case__ , """handle_key""" , [] ) handle += keys setattr(snake_case__ , """handle_key""" , snake_case__ ) return func return decorator class lowercase( __a ): '''simple docstring''' def __new__( cls: str, a_: Optional[Any], a_: List[Any], a_: Optional[Any] ): '''simple docstring''' _snake_case : Optional[int] = super().__new__(cls, a_, a_, a_ ) if not hasattr(a_, """key_handler""" ): setattr(a_, """key_handler""", {} ) setattr(a_, """handle_input""", KeyHandler.handle_input ) for value in attrs.values(): _snake_case : List[Any] = getattr(a_, """handle_key""", [] ) for key in handled_keys: _snake_case : Dict = value return new_cls @staticmethod def UpperCamelCase_ ( cls: str ): '''simple docstring''' _snake_case : List[Any] = get_character() if char != KEYMAP["undefined"]: _snake_case : Union[str, Any] = ord(a_ ) _snake_case : Optional[int] = cls.key_handler.get(a_ ) if handler: _snake_case : Optional[int] = char return handler(cls ) else: return None def UpperCAmelCase__ (cls : Union[str, Any] ): """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
64
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser A_ = re.compile(r'''\s+''') def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" return {"hash": hashlib.mda(re.sub(snake_case__ , """""" , example["""content"""] ).encode("""utf-8""" ) ).hexdigest()} def UpperCAmelCase__ (snake_case__ : Dict ): """simple docstring""" _snake_case : Any = [len(snake_case__ ) for line in example["""content"""].splitlines()] return {"line_mean": np.mean(snake_case__ ), "line_max": max(snake_case__ )} def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" _snake_case : Tuple = np.mean([c.isalnum() for c in example["""content"""]] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : List[Any] ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example["""hash"""] ) return True else: return False def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : List[str]=5 ): """simple docstring""" _snake_case : Any = ["""auto-generated""", """autogenerated""", """automatically generated"""] _snake_case : Tuple = example["""content"""].splitlines() for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Union[str, Any]=5 , snake_case__ : Any=0.05 ): """simple docstring""" _snake_case : Optional[Any] = ["""unit tests""", """test file""", """configuration file"""] _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : Dict = 0 _snake_case : str = 0 # first test for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _snake_case : Optional[int] = example["""content"""].count("""\n""" ) _snake_case : Tuple = int(coeff * nlines ) for line in lines: count_config += line.lower().count("""config""" ) count_test += line.lower().count("""test""" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Optional[int] = ["""def """, """class """, """for """, """while """] _snake_case : str = example["""content"""].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : List[str]=4 ): """simple docstring""" _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : str = 0 for line in lines: counter += line.lower().count("""=""" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase__ (snake_case__ : List[str] ): """simple docstring""" _snake_case : Optional[Any] = tokenizer(example["""content"""] , truncation=snake_case__ )["""input_ids"""] _snake_case : Optional[Any] = len(example["""content"""] ) / len(snake_case__ ) return {"ratio": ratio} def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[int] = {} results.update(get_hash(snake_case__ ) ) results.update(line_stats(snake_case__ ) ) results.update(alpha_stats(snake_case__ ) ) results.update(char_token_ratio(snake_case__ ) ) results.update(is_autogenerated(snake_case__ ) ) results.update(is_config_or_test(snake_case__ ) ) results.update(has_no_keywords(snake_case__ ) ) results.update(has_few_assignments(snake_case__ ) ) return results def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : List[str] ): """simple docstring""" if not check_uniques(snake_case__ , snake_case__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" with open(snake_case__ , """rb""" ) as f_in: with gzip.open(str(snake_case__ ) + """.gz""" , """wb""" , compresslevel=6 ) as f_out: shutil.copyfileobj(snake_case__ , snake_case__ ) os.unlink(snake_case__ ) # Settings A_ = HfArgumentParser(PreprocessingArguments) A_ = parser.parse_args() if args.num_workers is None: A_ = multiprocessing.cpu_count() A_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset A_ = time.time() A_ = load_dataset(args.dataset_name, split='''train''') print(F'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing A_ = time.time() A_ = ds.map(preprocess, num_proc=args.num_workers) print(F'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes A_ = set(ds.unique('''hash''')) A_ = len(uniques) / len(ds) print(F'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics A_ = time.time() A_ = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F'''Time to filter dataset: {time.time()-t_start:.2f}''') print(F'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: A_ = time.time() A_ , A_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(F'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file A_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) A_ = output_dir / '''data''' data_dir.mkdir(exist_ok=True) A_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): A_ = str(data_dir / F'''file-{file_number+1:012}.json''') A_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'''Time to save dataset: {time.time()-t_start:.2f}''')
64
1
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : int = data _snake_case : Dict = [0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def UpperCamelCase_ ( a_: Optional[Any], a_: Dict ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xffffffff def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) _snake_case : Optional[int] = self.data + padding + struct.pack(""">Q""", 8 * len(self.data ) ) return padded_data def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def UpperCamelCase_ ( self: Optional[Any], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = list(struct.unpack(""">16L""", a_ ) ) + [0] * 64 for i in range(16, 80 ): _snake_case : List[Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = self.padding() _snake_case : str = self.split_blocks() for block in self.blocks: _snake_case : Any = self.expand_block(a_ ) _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = self.h for i in range(0, 80 ): if 0 <= i < 20: _snake_case : int = (b & c) | ((~b) & d) _snake_case : str = 0X5a827999 elif 20 <= i < 40: _snake_case : Optional[int] = b ^ c ^ d _snake_case : str = 0X6ed9eba1 elif 40 <= i < 60: _snake_case : List[Any] = (b & c) | (b & d) | (c & d) _snake_case : List[Any] = 0X8f1bbcdc elif 60 <= i < 80: _snake_case : List[Any] = b ^ c ^ d _snake_case : int = 0Xca62c1d6 _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = ( self.rotate(a_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(a_, 30 ), c, d, ) _snake_case : Union[str, Any] = ( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = B"""Test String""" assert SHAaHash(snake_case__ ).final_hash() == hashlib.shaa(snake_case__ ).hexdigest() # noqa: S324 def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _snake_case : Union[str, Any] = parser.parse_args() _snake_case : List[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _snake_case : str = f.read() else: _snake_case : int = bytes(snake_case__ , """utf-8""" ) print(SHAaHash(snake_case__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
64
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase( unittest.TestCase ): '''simple docstring''' @property def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Any = ort.SessionOptions() _snake_case : Union[str, Any] = False return options def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _snake_case : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _snake_case : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _snake_case : Optional[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""", revision="""onnx""", safety_checker=a_, feature_extractor=a_, provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : Optional[Any] = """A red cat sitting on a park bench""" _snake_case : Optional[int] = np.random.RandomState(0 ) _snake_case : Any = pipe( prompt=a_, image=a_, mask_image=a_, strength=0.75, guidance_scale=7.5, num_inference_steps=15, generator=a_, output_type="""np""", ) _snake_case : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
64
1
"""simple docstring""" import math def UpperCAmelCase__ (snake_case__ : float , snake_case__ : float ): """simple docstring""" if ( not isinstance(snake_case__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * power_factor def UpperCAmelCase__ (snake_case__ : float , snake_case__ : float ): """simple docstring""" if ( not isinstance(snake_case__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
64
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() A_ = logging.get_logger(__name__) A_ = { '''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''', '''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''', } A_ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Dict , snake_case__ : Any , snake_case__ : str , snake_case__ : str ): """simple docstring""" for attribute in key.split(""".""" ): _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ) if weight_type is not None: _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ).shape else: _snake_case : Optional[Any] = hf_pointer.shape assert hf_shape == value.shape, ( 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": _snake_case : int = value elif weight_type == "weight_g": _snake_case : str = value elif weight_type == "weight_v": _snake_case : Tuple = value elif weight_type == "bias": _snake_case : List[str] = value else: _snake_case : int = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str] ): """simple docstring""" _snake_case : List[Any] = [] _snake_case : Optional[Any] = fairseq_model.state_dict() _snake_case : str = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _snake_case : Optional[Any] = None for name, value in fairseq_dict.items(): _snake_case : Optional[Any] = False if "conv_layers" in name: load_conv_layer( snake_case__ , snake_case__ , snake_case__ , snake_case__ , hf_model.config.feat_extract_norm == """group""" , ) _snake_case : Dict = True elif name.split(""".""" )[0] == "proj": _snake_case : Dict = fairseq_model.proj _snake_case : Optional[int] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _snake_case : Dict = True if "*" in mapped_key: _snake_case : Optional[int] = name.split(snake_case__ )[0].split(""".""" )[-2] _snake_case : Union[str, Any] = mapped_key.replace("""*""" , snake_case__ ) if "weight_g" in name: _snake_case : str = """weight_g""" elif "weight_v" in name: _snake_case : Optional[Any] = """weight_v""" elif "bias" in name: _snake_case : Union[str, Any] = """bias""" elif "weight" in name: _snake_case : int = """weight""" else: _snake_case : Optional[int] = None set_recursively(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) continue if not is_used: unused_weights.append(snake_case__ ) logger.warning(F"Unused weights: {unused_weights}" ) return proj_weight def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : int ): """simple docstring""" _snake_case : Any = full_name.split("""conv_layers.""" )[-1] _snake_case : Optional[int] = name.split(""".""" ) _snake_case : List[str] = int(items[0] ) _snake_case : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _snake_case : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _snake_case : List[Any] = 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _snake_case : int = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _snake_case : List[str] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case , _snake_case : Optional[Any] = emb.weight.shape _snake_case : Optional[int] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _snake_case : Union[str, Any] = emb.weight.data return lin_layer def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" with open(snake_case__ , """r""" , encoding="""utf-8""" ) as f: _snake_case : Any = f.readlines() _snake_case : Optional[Any] = [line.split(""" """ )[0] for line in lines] _snake_case : str = len(snake_case__ ) _snake_case : Tuple = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(snake_case__ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def UpperCAmelCase__ (snake_case__ : int , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Dict , snake_case__ : List[Any] , snake_case__ : str , snake_case__ : Union[str, Any] , ): """simple docstring""" _snake_case : Optional[int] = WavaVecaConfig.from_pretrained(snake_case__ ) _snake_case : List[str] = SpeechaTextaConfig.from_pretrained( snake_case__ , vocab_size=snake_case__ , decoder_layers=snake_case__ , do_stable_layer_norm=snake_case__ ) _snake_case : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case__ , return_attention_mask=snake_case__ , ) _snake_case , _snake_case , _snake_case : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) _snake_case : Optional[Any] = model[0].eval() # set weights for wav2vec2 encoder _snake_case : Any = WavaVecaModel(snake_case__ ) _snake_case : Optional[Any] = recursively_load_weights_wavaveca(model.encoder , snake_case__ ) _snake_case : Optional[Any] = SpeechaTextaForCausalLM(snake_case__ ) _snake_case , _snake_case : List[str] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case__ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) _snake_case : Any = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(F"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) _snake_case : Any = SpeechEncoderDecoderModel(encoder=snake_case__ , decoder=snake_case__ ) _snake_case : Any = False # add projection layer _snake_case : int = nn.Parameter(projection_layer.weight ) _snake_case : Any = nn.Parameter(projection_layer.bias ) _snake_case : Any = create_vocab_dict(snake_case__ ) with open(os.path.join(snake_case__ , """vocab.json""" ) , """w""" ) as fp: json.dump(snake_case__ , snake_case__ ) _snake_case : Dict = SpeechaTextaTokenizer(os.path.join(snake_case__ , """vocab.json""" ) ) tokenizer.save_pretrained(snake_case__ ) _snake_case : str = hf_wavavec.config.to_dict() _snake_case : List[str] = tokenizer.pad_token_id _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Union[str, Any] = tokenizer.eos_token_id _snake_case : Optional[Any] = """speech_to_text_2""" _snake_case : Optional[int] = """wav2vec2""" _snake_case : Tuple = SpeechEncoderDecoderConfig.from_dict(snake_case__ ) hf_wavavec.save_pretrained(snake_case__ ) feature_extractor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = 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( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=1_02_24, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') A_ = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
64
1
"""simple docstring""" # 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 from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class lowercase( __a ): '''simple docstring''' lowercase__ = "Salesforce/blip-image-captioning-base" lowercase__ = ( "This is a tool that generates a description of an image. It takes an input named `image` which should be the " "image to caption, and returns a text that contains the description in English." ) lowercase__ = "image_captioner" lowercase__ = AutoModelForVisionaSeq lowercase__ = ["image"] lowercase__ = ["text"] def __init__( self: Optional[Any], *a_: List[str], **a_: List[Any] ): '''simple docstring''' requires_backends(self, ["""vision"""] ) super().__init__(*a_, **a_ ) def UpperCamelCase_ ( self: str, a_: "Image" ): '''simple docstring''' return self.pre_processor(images=a_, return_tensors="""pt""" ) def UpperCamelCase_ ( self: Dict, a_: Dict ): '''simple docstring''' return self.model.generate(**a_ ) def UpperCamelCase_ ( self: List[Any], a_: Tuple ): '''simple docstring''' return self.pre_processor.batch_decode(a_, skip_special_tokens=a_ )[0].strip()
64
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A_ = 16 A_ = 32 def UpperCAmelCase__ (snake_case__ : Accelerator , snake_case__ : int = 16 ): """simple docstring""" _snake_case : Optional[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _snake_case : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(snake_case__ : Any ): # max_length=None => use the model max length (it's actually the default) _snake_case : Any = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _snake_case : List[Any] = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case : int = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _snake_case : Optional[int] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _snake_case : str = 16 elif accelerator.mixed_precision != "no": _snake_case : Optional[int] = 8 else: _snake_case : Optional[int] = None return tokenizer.pad( snake_case__ , padding="""longest""" , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _snake_case : Optional[int] = DataLoader( tokenized_datasets["""train"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) _snake_case : Dict = DataLoader( tokenized_datasets["""validation"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders A_ = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any ): """simple docstring""" if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , snake_case__ ) == "1": _snake_case : List[Any] = 2 # Initialize accelerator _snake_case : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case : Tuple = config["""lr"""] _snake_case : str = int(config["""num_epochs"""] ) _snake_case : Union[str, Any] = int(config["""seed"""] ) _snake_case : Union[str, Any] = int(config["""batch_size"""] ) _snake_case : List[str] = evaluate.load("""glue""" , """mrpc""" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case__ ) def inner_training_loop(snake_case__ : Union[str, Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case : List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _snake_case : Tuple = model.to(accelerator.device ) # Instantiate optimizer _snake_case : str = AdamW(params=model.parameters() , lr=snake_case__ ) _snake_case , _snake_case : Optional[int] = get_dataloaders(snake_case__ , snake_case__ ) # Instantiate scheduler _snake_case : str = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=1_00 , num_training_steps=(len(snake_case__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : List[str] = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _snake_case : int = model(**snake_case__ ) _snake_case : str = outputs.loss accelerator.backward(snake_case__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _snake_case : int = model(**snake_case__ ) _snake_case : Optional[Any] = outputs.logits.argmax(dim=-1 ) _snake_case , _snake_case : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) _snake_case : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , snake_case__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=snake_case__ , default=snake_case__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _snake_case : Dict = parser.parse_args() _snake_case : int = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
64
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { '''configuration_clap''': [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapAudioConfig''', '''ClapConfig''', '''ClapTextConfig''', ], '''processing_clap''': ['''ClapProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapModel''', '''ClapPreTrainedModel''', '''ClapTextModel''', '''ClapTextModelWithProjection''', '''ClapAudioModel''', '''ClapAudioModelWithProjection''', ] A_ = ['''ClapFeatureExtractor'''] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def UpperCAmelCase__ (snake_case__ : Optional[int] , snake_case__ : Any=7 ): """simple docstring""" _snake_case : Any = None if token is not None: _snake_case : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} # The id of a workflow (not of a workflow run) _snake_case : List[str] = """636036""" _snake_case : Union[str, Any] = F"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}" _snake_case : str = requests.get(snake_case__ , headers=snake_case__ ).json() return result["workflow_runs"] def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : str = get_daily_ci_runs(snake_case__ ) _snake_case : str = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _snake_case : List[str] = workflow_run["""id"""] break return workflow_run_id def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Union[str, Any] , snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[Any] = get_last_daily_ci_runs(snake_case__ ) if workflow_run_id is not None: _snake_case : Optional[Any] = get_artifacts_links(worflow_run_id=snake_case__ , token=snake_case__ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _snake_case : Optional[int] = artifacts_links[artifact_name] download_artifact( artifact_name=snake_case__ , artifact_url=snake_case__ , output_dir=snake_case__ , token=snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] , snake_case__ : List[str] , snake_case__ : int ): """simple docstring""" get_last_daily_ci_artifacts(snake_case__ , snake_case__ , snake_case__ ) _snake_case : int = {} for artifact_name in artifact_names: _snake_case : int = os.path.join(snake_case__ , F"{artifact_name}.zip" ) if os.path.isfile(snake_case__ ): _snake_case : Tuple = {} with zipfile.ZipFile(snake_case__ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case__ ): # read the file with z.open(snake_case__ ) as f: _snake_case : Any = f.read().decode("""UTF-8""" ) return results
64
1
"""simple docstring""" import math from collections.abc import Callable def UpperCAmelCase__ (snake_case__ : Callable[[float], float] , snake_case__ : float , snake_case__ : float ): """simple docstring""" _snake_case : float = xa _snake_case : float = xa while True: if x_n == x_na or function(snake_case__ ) == function(snake_case__ ): raise ZeroDivisionError("""float division by zero, could not find root""" ) _snake_case : float = x_na - ( function(snake_case__ ) / ((function(snake_case__ ) - function(snake_case__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na _snake_case : Dict = x_na _snake_case : Optional[Any] = x_na def UpperCAmelCase__ (snake_case__ : float ): """simple docstring""" return math.pow(snake_case__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
64
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging A_ = logging.get_logger(__name__) class lowercase: '''simple docstring''' lowercase__ = 42 lowercase__ = None @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Tuple, a_: int, a_: int, a_: str, **a_: Dict ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any], a_: List[str] ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.is_available(): raise RuntimeError( f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}." ) @classmethod def UpperCamelCase_ ( cls: Tuple ): '''simple docstring''' return f"`pip install {cls.pip_package or cls.name}`" class lowercase( __a ): '''simple docstring''' lowercase__ = "optuna" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def UpperCamelCase_ ( self: Union[str, Any], a_: List[Any], a_: int, a_: str, **a_: List[str] ): '''simple docstring''' return run_hp_search_optuna(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], a_: Any ): '''simple docstring''' return default_hp_space_optuna(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "ray" lowercase__ = "'ray[tune]'" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_ray_available() def UpperCamelCase_ ( self: int, a_: Optional[Any], a_: int, a_: str, **a_: List[Any] ): '''simple docstring''' return run_hp_search_ray(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Tuple ): '''simple docstring''' return default_hp_space_ray(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "sigopt" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def UpperCamelCase_ ( self: Dict, a_: str, a_: int, a_: str, **a_: int ): '''simple docstring''' return run_hp_search_sigopt(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: List[str] ): '''simple docstring''' return default_hp_space_sigopt(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "wandb" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def UpperCamelCase_ ( self: Optional[Any], a_: str, a_: int, a_: str, **a_: Union[str, Any] ): '''simple docstring''' return run_hp_search_wandb(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Any ): '''simple docstring''' return default_hp_space_wandb(a_ ) A_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def UpperCAmelCase__ (): """simple docstring""" _snake_case : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(snake_case__ ) > 0: _snake_case : Any = available_backends[0].name if len(snake_case__ ) > 1: logger.info( F"{len(snake_case__ )} hyperparameter search backends available. Using {name} as the default." ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( F" - To install {backend.name} run {backend.pip_install()}" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
64
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class lowercase( __a ): '''simple docstring''' def __init__( self: List[Any], a_: List[Any], a_: Tuple ): '''simple docstring''' super().__init__() self.register_modules(unet=a_, scheduler=a_ ) @torch.no_grad() def __call__( self: Optional[Any], a_: int = 1, a_: int = 100, a_: Optional[Union[torch.Generator, List[torch.Generator]]] = None, a_: Optional[float] = None, a_: bool = True, ): '''simple docstring''' if audio_length_in_s is None: _snake_case : Dict = self.unet.config.sample_size / self.unet.config.sample_rate _snake_case : Any = audio_length_in_s * self.unet.config.sample_rate _snake_case : int = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f"{audio_length_in_s} is too small. Make sure it's bigger or equal to" f" {3 * down_scale_factor / self.unet.config.sample_rate}." ) _snake_case : str = int(a_ ) if sample_size % down_scale_factor != 0: _snake_case : Optional[Any] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f"{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled" f" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising" """ process.""" ) _snake_case : List[Any] = int(a_ ) _snake_case : Dict = next(iter(self.unet.parameters() ) ).dtype _snake_case : Any = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(a_, a_ ) and len(a_ ) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(a_ )}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) _snake_case : Union[str, Any] = randn_tensor(a_, generator=a_, device=self.device, dtype=a_ ) # set step values self.scheduler.set_timesteps(a_, device=audio.device ) _snake_case : Union[str, Any] = self.scheduler.timesteps.to(a_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _snake_case : Any = self.unet(a_, a_ ).sample # 2. compute previous image: x_t -> t_t-1 _snake_case : int = self.scheduler.step(a_, a_, a_ ).prev_sample _snake_case : Any = audio.clamp(-1, 1 ).float().cpu().numpy() _snake_case : str = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=a_ )
64
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowercase( __a ): '''simple docstring''' lowercase__ = ["image_processor", "tokenizer"] lowercase__ = "AutoImageProcessor" lowercase__ = "AutoTokenizer" def __init__( self: List[str], a_: List[str]=None, a_: Tuple=None, **a_: Tuple ): '''simple docstring''' _snake_case : str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""", a_, ) _snake_case : str = kwargs.pop("""feature_extractor""" ) _snake_case : Union[str, Any] = 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__(a_, a_ ) _snake_case : Dict = self.image_processor _snake_case : Any = False def __call__( self: Any, *a_: Any, **a_: Tuple ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*a_, **a_ ) _snake_case : Dict = kwargs.pop("""images""", a_ ) _snake_case : Optional[Any] = kwargs.pop("""text""", a_ ) if len(a_ ) > 0: _snake_case : Optional[int] = args[0] _snake_case : Tuple = args[1:] if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: _snake_case : Tuple = self.image_processor(a_, *a_, **a_ ) if text is not None: _snake_case : Tuple = self.tokenizer(a_, **a_ ) if text is None: return inputs elif images is None: return encodings else: _snake_case : List[str] = encodings["""input_ids"""] return inputs def UpperCamelCase_ ( self: Optional[int], *a_: Tuple, **a_: List[str] ): '''simple docstring''' return self.tokenizer.batch_decode(*a_, **a_ ) def UpperCamelCase_ ( self: int, *a_: List[str], **a_: int ): '''simple docstring''' return self.tokenizer.decode(*a_, **a_ ) @contextmanager def UpperCamelCase_ ( self: Dict ): '''simple docstring''' warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your images inputs, or in a separate call.""" ) _snake_case : Any = True _snake_case : Optional[int] = self.tokenizer yield _snake_case : int = self.image_processor _snake_case : Optional[int] = False def UpperCamelCase_ ( self: Dict, a_: Optional[Any], a_: str=False, a_: Optional[Any]=None ): '''simple docstring''' if added_vocab is None: _snake_case : Dict = self.tokenizer.get_added_vocab() _snake_case : str = {} while tokens: _snake_case : Union[str, Any] = re.search(r"""<s_(.*?)>""", a_, re.IGNORECASE ) if start_token is None: break _snake_case : List[Any] = start_token.group(1 ) _snake_case : str = re.search(rf"</s_{key}>", a_, re.IGNORECASE ) _snake_case : Dict = start_token.group() if end_token is None: _snake_case : List[Any] = tokens.replace(a_, """""" ) else: _snake_case : List[str] = end_token.group() _snake_case : str = re.escape(a_ ) _snake_case : str = re.escape(a_ ) _snake_case : Union[str, Any] = re.search(f"{start_token_escaped}(.*?){end_token_escaped}", a_, re.IGNORECASE ) if content is not None: _snake_case : int = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node _snake_case : List[Any] = self.tokenajson(a_, is_inner_value=a_, added_vocab=a_ ) if value: if len(a_ ) == 1: _snake_case : List[str] = value[0] _snake_case : List[str] = value else: # leaf nodes _snake_case : Tuple = [] for leaf in content.split(r"""<sep/>""" ): _snake_case : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": _snake_case : int = leaf[1:-2] # for categorical special tokens output[key].append(a_ ) if len(output[key] ) == 1: _snake_case : int = output[key][0] _snake_case : Any = tokens[tokens.find(a_ ) + len(a_ ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=a_, added_vocab=a_ ) if len(a_ ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""", a_, ) return self.image_processor_class @property def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""", a_, ) return self.image_processor
64
1
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Tuple , snake_case__ : Any , snake_case__ : int , snake_case__ : Optional[int]=True , snake_case__ : Optional[int]="pt" ): """simple docstring""" _snake_case : Dict = {"""add_prefix_space""": True} if isinstance(snake_case__ , snake_case__ ) and not line.startswith(""" """ ) else {} _snake_case : Optional[Any] = padding_side return tokenizer( [line] , max_length=snake_case__ , padding="""max_length""" if pad_to_max_length else None , truncation=snake_case__ , return_tensors=snake_case__ , add_special_tokens=snake_case__ , **snake_case__ , ) def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : Dict , snake_case__ : Any=None , ): """simple docstring""" _snake_case : List[Any] = input_ids.ne(snake_case__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class lowercase( __a ): '''simple docstring''' def __init__( self: str, a_: Any, a_: Union[str, Any], a_: Dict, a_: Dict, a_: int="train", a_: Any=None, a_: Any=None, a_: Any=None, a_: Tuple="", ): '''simple docstring''' super().__init__() _snake_case : str = Path(a_ ).joinpath(type_path + """.source""" ) _snake_case : Optional[int] = Path(a_ ).joinpath(type_path + """.target""" ) _snake_case : Optional[Any] = self.get_char_lens(self.src_file ) _snake_case : Tuple = max_source_length _snake_case : Any = max_target_length assert min(self.src_lens ) > 0, f"found empty line in {self.src_file}" _snake_case : List[str] = tokenizer _snake_case : Union[str, Any] = prefix if n_obs is not None: _snake_case : List[Any] = self.src_lens[:n_obs] _snake_case : Dict = src_lang _snake_case : List[Any] = tgt_lang def __len__( self: Any ): '''simple docstring''' return len(self.src_lens ) def __getitem__( self: Union[str, Any], a_: List[Any] ): '''simple docstring''' _snake_case : Optional[int] = index + 1 # linecache starts at 1 _snake_case : Optional[Any] = self.prefix + linecache.getline(str(self.src_file ), a_ ).rstrip("""\n""" ) _snake_case : int = linecache.getline(str(self.tgt_file ), a_ ).rstrip("""\n""" ) assert source_line, f"empty source line for index {index}" assert tgt_line, f"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer, a_ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _snake_case : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer, a_ ) else self.tokenizer ) _snake_case : str = self.tokenizer.generator if isinstance(self.tokenizer, a_ ) else self.tokenizer _snake_case : Tuple = encode_line(a_, a_, self.max_source_length, """right""" ) _snake_case : Optional[Any] = encode_line(a_, a_, self.max_target_length, """right""" ) _snake_case : Optional[int] = source_inputs["""input_ids"""].squeeze() _snake_case : Optional[Any] = target_inputs["""input_ids"""].squeeze() _snake_case : List[Any] = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def UpperCamelCase_ ( a_: Union[str, Any] ): '''simple docstring''' return [len(a_ ) for x in Path(a_ ).open().readlines()] def UpperCamelCase_ ( self: Optional[int], a_: List[str] ): '''simple docstring''' _snake_case : Any = torch.stack([x["""input_ids"""] for x in batch] ) _snake_case : Optional[int] = torch.stack([x["""attention_mask"""] for x in batch] ) _snake_case : Tuple = torch.stack([x["""decoder_input_ids"""] for x in batch] ) _snake_case : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer, a_ ) else self.tokenizer.pad_token_id ) _snake_case : str = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer, a_ ) else self.tokenizer.pad_token_id ) _snake_case : Optional[int] = trim_batch(a_, a_ ) _snake_case , _snake_case : List[Any] = trim_batch(a_, a_, attention_mask=a_ ) _snake_case : Tuple = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch A_ = getLogger(__name__) def UpperCAmelCase__ (snake_case__ : List[List] ): """simple docstring""" return list(itertools.chain.from_iterable(snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Any = get_git_info() save_json(snake_case__ , os.path.join(snake_case__ , """git_log.json""" ) ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[Any] , snake_case__ : Any=4 , **snake_case__ : str ): """simple docstring""" with open(snake_case__ , """w""" ) as f: json.dump(snake_case__ , snake_case__ , indent=snake_case__ , **snake_case__ ) def UpperCAmelCase__ (snake_case__ : Tuple ): """simple docstring""" with open(snake_case__ ) as f: return json.load(snake_case__ ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = git.Repo(search_parent_directories=snake_case__ ) _snake_case : List[str] = { """repo_id""": str(snake_case__ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def UpperCAmelCase__ (snake_case__ : Callable , snake_case__ : Iterable ): """simple docstring""" return list(map(snake_case__ , snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : Union[str, Any] ): """simple docstring""" with open(snake_case__ , """wb""" ) as f: return pickle.dump(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" def remove_articles(snake_case__ : Optional[Any] ): return re.sub(R"""\b(a|an|the)\b""" , """ """ , snake_case__ ) def white_space_fix(snake_case__ : Dict ): return " ".join(text.split() ) def remove_punc(snake_case__ : Any ): _snake_case : List[str] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(snake_case__ : Tuple ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(snake_case__ ) ) ) ) def UpperCAmelCase__ (snake_case__ : Optional[int] , snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Tuple = normalize_answer(snake_case__ ).split() _snake_case : Tuple = normalize_answer(snake_case__ ).split() _snake_case : List[str] = Counter(snake_case__ ) & Counter(snake_case__ ) _snake_case : Dict = sum(common.values() ) if num_same == 0: return 0 _snake_case : List[str] = 1.0 * num_same / len(snake_case__ ) _snake_case : Optional[int] = 1.0 * num_same / len(snake_case__ ) _snake_case : List[Any] = (2 * precision * recall) / (precision + recall) return fa def UpperCAmelCase__ (snake_case__ : Union[str, Any] , snake_case__ : Tuple ): """simple docstring""" return normalize_answer(snake_case__ ) == normalize_answer(snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : List[str] ): """simple docstring""" assert len(snake_case__ ) == len(snake_case__ ) _snake_case : Union[str, Any] = 0 for hypo, pred in zip(snake_case__ , snake_case__ ): em += exact_match_score(snake_case__ , snake_case__ ) if len(snake_case__ ) > 0: em /= len(snake_case__ ) return {"em": em} def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" return model_prefix.startswith("""rag""" ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int , snake_case__ : str ): """simple docstring""" _snake_case : int = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _snake_case : List[Any] = """dropout_rate""" for p in extra_params: if getattr(snake_case__ , snake_case__ , snake_case__ ): if not hasattr(snake_case__ , snake_case__ ) and not hasattr(snake_case__ , equivalent_param[p] ): logger.info("""config doesn't have a `{}` attribute""".format(snake_case__ ) ) delattr(snake_case__ , snake_case__ ) continue _snake_case : str = p if hasattr(snake_case__ , snake_case__ ) else equivalent_param[p] setattr(snake_case__ , snake_case__ , getattr(snake_case__ , snake_case__ ) ) delattr(snake_case__ , snake_case__ ) return hparams, config
64
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : int = 0.00 _snake_case : int = 0 for resistor in resistors: if resistor <= 0: _snake_case : Dict = F"Resistor at index {index} has a negative or zero value!" raise ValueError(snake_case__ ) first_sum += 1 / float(snake_case__ ) index += 1 return 1 / first_sum def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : Union[str, Any] = 0.00 _snake_case : Any = 0 for resistor in resistors: sum_r += resistor if resistor < 0: _snake_case : Any = F"Resistor at index {index} has a negative value!" raise ValueError(snake_case__ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
64
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" def merge(snake_case__ : list , snake_case__ : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(snake_case__ ) <= 1: return collection _snake_case : str = len(snake_case__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
64
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''', }, '''merges_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''Salesforce/codegen-350M-mono''': ( '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json''' ), }, } A_ = { '''Salesforce/codegen-350M-mono''': 20_48, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] lowercase__ = CodeGenTokenizer def __init__( self: Union[str, Any], a_: List[Any]=None, a_: str=None, a_: str=None, a_: Dict="<|endoftext|>", a_: Tuple="<|endoftext|>", a_: str="<|endoftext|>", a_: List[Any]=False, **a_: List[str], ): '''simple docstring''' super().__init__( a_, a_, tokenizer_file=a_, unk_token=a_, bos_token=a_, eos_token=a_, add_prefix_space=a_, **a_, ) if kwargs.pop("""add_bos_token""", a_ ): _snake_case : str = kwargs.pop("""name_or_path""", """""" ) raise ValueError( """Currenty GPT2's fast tokenizer does NOT support adding a BOS token.""" """Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n""" f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n" f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n" """This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.""" """ so that the fast tokenizer works correctly.""" ) _snake_case : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : Dict = getattr(a_, pre_tok_state.pop("""type""" ) ) _snake_case : Dict = add_prefix_space _snake_case : str = pre_tok_class(**a_ ) _snake_case : List[Any] = add_prefix_space def UpperCamelCase_ ( self: Any, *a_: Any, **a_: int ): '''simple docstring''' _snake_case : Optional[int] = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], *a_: Any, **a_: List[str] ): '''simple docstring''' _snake_case : Dict = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : List[Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ ) def UpperCamelCase_ ( self: str, a_: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], a_: bool = False, a_: bool = None, a_: Optional[List[str]] = None, **a_: List[str], ): '''simple docstring''' _snake_case : Any = super().decode( token_ids=a_, skip_special_tokens=a_, clean_up_tokenization_spaces=a_, **a_, ) if truncate_before_pattern is not None and len(a_ ) > 0: _snake_case : List[str] = self.truncate(a_, a_ ) return decoded_text def UpperCamelCase_ ( self: Dict, a_: Tuple, a_: Optional[Any] ): '''simple docstring''' def find_re(a_: Dict, a_: str, a_: Union[str, Any] ): _snake_case : Any = pattern.search(a_, a_ ) return m.start() if m else -1 _snake_case : Tuple = [re.compile(a_, re.MULTILINE ) for pattern in truncate_before_pattern] _snake_case : List[Any] = list(re.finditer("""^print""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : int = completion[: prints[1].start()] _snake_case : List[str] = list(re.finditer("""^def""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : List[Any] = completion[: defs[1].start()] _snake_case : int = 0 _snake_case : List[Any] = [ pos for pos in [find_re(a_, a_, a_ ) for terminal in terminals] if pos != -1 ] if len(a_ ) > 0: return completion[: min(a_ )] else: return completion
64
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ = { '''configuration_roberta_prelayernorm''': [ '''ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaPreLayerNormConfig''', '''RobertaPreLayerNormOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaPreLayerNormForCausalLM''', '''RobertaPreLayerNormForMaskedLM''', '''RobertaPreLayerNormForMultipleChoice''', '''RobertaPreLayerNormForQuestionAnswering''', '''RobertaPreLayerNormForSequenceClassification''', '''RobertaPreLayerNormForTokenClassification''', '''RobertaPreLayerNormModel''', '''RobertaPreLayerNormPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaPreLayerNormForCausalLM''', '''TFRobertaPreLayerNormForMaskedLM''', '''TFRobertaPreLayerNormForMultipleChoice''', '''TFRobertaPreLayerNormForQuestionAnswering''', '''TFRobertaPreLayerNormForSequenceClassification''', '''TFRobertaPreLayerNormForTokenClassification''', '''TFRobertaPreLayerNormMainLayer''', '''TFRobertaPreLayerNormModel''', '''TFRobertaPreLayerNormPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''FlaxRobertaPreLayerNormForCausalLM''', '''FlaxRobertaPreLayerNormForMaskedLM''', '''FlaxRobertaPreLayerNormForMultipleChoice''', '''FlaxRobertaPreLayerNormForQuestionAnswering''', '''FlaxRobertaPreLayerNormForSequenceClassification''', '''FlaxRobertaPreLayerNormForTokenClassification''', '''FlaxRobertaPreLayerNormModel''', '''FlaxRobertaPreLayerNormPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : List[Any] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _snake_case : Tuple = 1_92 _snake_case : Any = 7_68 _snake_case : Any = 12 _snake_case : List[Any] = 3 _snake_case : int = [8_00, 13_33] _snake_case : Tuple = False elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = 3_30 _snake_case : List[str] = 14 _snake_case : List[str] = 6 _snake_case : Union[str, Any] = 13_20 elif "yolos_s" in yolos_name: _snake_case : Union[str, Any] = 3_84 _snake_case : List[str] = 15_36 _snake_case : Any = 12 _snake_case : Optional[int] = 6 elif "yolos_b" in yolos_name: _snake_case : Dict = [8_00, 13_44] _snake_case : str = 91 _snake_case : Optional[Any] = """huggingface/label-files""" _snake_case : str = """coco-detection-id2label.json""" _snake_case : str = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="""dataset""" ) , """r""" ) ) _snake_case : Union[str, Any] = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[str] = idalabel _snake_case : List[str] = {v: k for k, v in idalabel.items()} return config def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosConfig , snake_case__ : bool = False ): """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : int = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) _snake_case : Union[str, Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Any = in_proj_weight[: config.hidden_size, :] _snake_case : Optional[Any] = in_proj_bias[: config.hidden_size] _snake_case : Optional[int] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Tuple = in_proj_weight[-config.hidden_size :, :] _snake_case : List[Any] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" if "backbone" in name: _snake_case : str = name.replace("""backbone""" , """vit""" ) if "cls_token" in name: _snake_case : Union[str, Any] = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "det_token" in name: _snake_case : str = name.replace("""det_token""" , """embeddings.detection_tokens""" ) if "mid_pos_embed" in name: _snake_case : str = name.replace("""mid_pos_embed""" , """encoder.mid_position_embeddings""" ) if "pos_embed" in name: _snake_case : Tuple = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: _snake_case : str = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "blocks" in name: _snake_case : str = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: _snake_case : Any = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: _snake_case : str = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: _snake_case : List[str] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: _snake_case : str = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: _snake_case : List[str] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: _snake_case : int = name.replace("""mlp.fc2""" , """output.dense""" ) if "class_embed" in name: _snake_case : Union[str, Any] = name.replace("""class_embed""" , """class_labels_classifier""" ) if "bbox_embed" in name: _snake_case : str = name.replace("""bbox_embed""" , """bbox_predictor""" ) if "vit.norm" in name: _snake_case : Union[str, Any] = name.replace("""vit.norm""" , """vit.layernorm""" ) return name def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosForObjectDetection ): """simple docstring""" for key in orig_state_dict.copy().keys(): _snake_case : List[str] = orig_state_dict.pop(snake_case__ ) if "qkv" in key: _snake_case : Optional[Any] = key.split(""".""" ) _snake_case : Optional[Any] = int(key_split[2] ) _snake_case : Optional[int] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _snake_case : str = val[:dim, :] _snake_case : Optional[Any] = val[ dim : dim * 2, : ] _snake_case : Optional[Any] = val[-dim:, :] else: _snake_case : Dict = val[:dim] _snake_case : Any = val[dim : dim * 2] _snake_case : Dict = val[-dim:] else: _snake_case : Tuple = val return orig_state_dict def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Union[str, Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : str , snake_case__ : bool = False ): """simple docstring""" _snake_case : Optional[Any] = get_yolos_config(snake_case__ ) # load original state_dict _snake_case : Optional[int] = torch.load(snake_case__ , map_location="""cpu""" )["""model"""] # load 🤗 model _snake_case : Optional[Any] = YolosForObjectDetection(snake_case__ ) model.eval() _snake_case : Optional[Any] = convert_state_dict(snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ ) # Check outputs on an image, prepared by YolosImageProcessor _snake_case : List[str] = 8_00 if yolos_name != """yolos_ti""" else 5_12 _snake_case : Optional[int] = YolosImageProcessor(format="""coco_detection""" , size=snake_case__ ) _snake_case : Optional[Any] = image_processor(images=prepare_img() , return_tensors="""pt""" ) _snake_case : Optional[Any] = model(**snake_case__ ) _snake_case , _snake_case : Optional[int] = outputs.logits, outputs.pred_boxes _snake_case , _snake_case : Dict = None, None if yolos_name == "yolos_ti": _snake_case : Optional[Any] = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) _snake_case : Tuple = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": _snake_case : List[str] = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) _snake_case : List[str] = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": _snake_case : Dict = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) _snake_case : Union[str, Any] = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) _snake_case : Optional[Any] = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": _snake_case : int = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) _snake_case : Optional[int] = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(F"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , snake_case__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , snake_case__ , atol=1e-4 ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if push_to_hub: _snake_case : Dict = { """yolos_ti""": """yolos-tiny""", """yolos_s_200_pre""": """yolos-small""", """yolos_s_300_pre""": """yolos-small-300""", """yolos_s_dWr""": """yolos-small-dwr""", """yolos_base""": """yolos-base""", } print("""Pushing to the hub...""" ) _snake_case : str = model_mapping[yolos_name] image_processor.push_to_hub(snake_case__ , organization="""hustvl""" ) model.push_to_hub(snake_case__ , organization="""hustvl""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.pth file).''' ) 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.''' ) A_ = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
64
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A_ = { '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''], '''tokenization_canine''': ['''CanineTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CanineForMultipleChoice''', '''CanineForQuestionAnswering''', '''CanineForSequenceClassification''', '''CanineForTokenClassification''', '''CanineLayer''', '''CanineModel''', '''CaninePreTrainedModel''', '''load_tf_weights_in_canine''', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str]=False ): """simple docstring""" _snake_case : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"module.blocks.{i}.norm1.weight", F"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((F"module.blocks.{i}.norm1.bias", F"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (F"module.blocks.{i}.attn.proj.weight", F"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.attn.proj.bias", F"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((F"module.blocks.{i}.norm2.weight", F"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((F"module.blocks.{i}.norm2.bias", F"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.weight", F"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.bias", F"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.weight", F"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.bias", F"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _snake_case : Any = [(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 UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : Dict , snake_case__ : List[str]=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _snake_case : List[Any] = """""" else: _snake_case : List[Any] = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.weight" ) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Optional[Any] = in_proj_weight[ : config.hidden_size, : ] _snake_case : Union[str, Any] = in_proj_bias[: config.hidden_size] _snake_case : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] _snake_case : List[str] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Tuple = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" _snake_case : List[str] = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : int ): """simple docstring""" _snake_case : Optional[Any] = dct.pop(snake_case__ ) _snake_case : Union[str, Any] = val def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : str ): """simple docstring""" _snake_case : str = ViTMSNConfig() _snake_case : Any = 10_00 _snake_case : Tuple = """datasets/huggingface/label-files""" _snake_case : Dict = """imagenet-1k-id2label.json""" _snake_case : int = json.load(open(hf_hub_download(snake_case__ , snake_case__ ) , """r""" ) ) _snake_case : Any = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[Any] = idalabel _snake_case : str = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: _snake_case : Tuple = 3_84 _snake_case : Dict = 15_36 _snake_case : Tuple = 6 elif "l16" in checkpoint_url: _snake_case : Any = 10_24 _snake_case : int = 40_96 _snake_case : str = 24 _snake_case : Optional[int] = 16 _snake_case : List[Any] = 0.1 elif "b4" in checkpoint_url: _snake_case : Tuple = 4 elif "l7" in checkpoint_url: _snake_case : int = 7 _snake_case : Dict = 10_24 _snake_case : Optional[Any] = 40_96 _snake_case : Any = 24 _snake_case : Union[str, Any] = 16 _snake_case : Optional[int] = 0.1 _snake_case : int = ViTMSNModel(snake_case__ ) _snake_case : Optional[int] = torch.hub.load_state_dict_from_url(snake_case__ , map_location="""cpu""" )["""target_encoder"""] _snake_case : List[str] = ViTImageProcessor(size=config.image_size ) remove_projection_head(snake_case__ ) _snake_case : List[str] = create_rename_keys(snake_case__ , base_model=snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_q_k_v(snake_case__ , snake_case__ , base_model=snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() _snake_case : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) _snake_case : str = ViTImageProcessor( size=config.image_size , image_mean=snake_case__ , image_std=snake_case__ ) _snake_case : Any = image_processor(images=snake_case__ , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) _snake_case : int = model(**snake_case__ ) _snake_case : List[Any] = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: _snake_case : Optional[Any] = torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] ) elif "b16" in checkpoint_url: _snake_case : str = torch.tensor([[14.28_89, -18.90_45, 11.72_81]] ) elif "l16" in checkpoint_url: _snake_case : Optional[int] = torch.tensor([[41.50_28, -22.86_81, 45.64_75]] ) elif "b4" in checkpoint_url: _snake_case : List[Any] = torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] ) else: _snake_case : Optional[int] = torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , snake_case__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A_ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
64
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" if not isinstance(snake_case__ , snake_case__ ): raise TypeError("""Input value must be an 'int' type""" ) _snake_case : Optional[int] = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
64
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str ): """simple docstring""" _snake_case : Optional[Any] = list(snake_case__ ) _snake_case : List[Any] = list(snake_case__ ) _snake_case : List[Any] = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count += 1 _snake_case : Any = """_""" if count > 1: return False else: return "".join(snake_case__ ) def UpperCAmelCase__ (snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [] while True: _snake_case : Union[str, Any] = ["""$"""] * len(snake_case__ ) _snake_case : int = [] for i in range(len(snake_case__ ) ): for j in range(i + 1 , len(snake_case__ ) ): _snake_case : List[Any] = compare_string(binary[i] , binary[j] ) if k is False: _snake_case : Dict = """*""" _snake_case : List[Any] = """*""" temp.append("""X""" ) for i in range(len(snake_case__ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case__ ) == 0: return pi _snake_case : Optional[int] = list(set(snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Sequence[float] ): """simple docstring""" _snake_case : Optional[int] = [] for minterm in minterms: _snake_case : Any = """""" for _ in range(snake_case__ ): _snake_case : Optional[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case__ ) return temp def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : int ): """simple docstring""" _snake_case : Dict = list(snake_case__ ) _snake_case : List[str] = list(snake_case__ ) _snake_case : Tuple = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCAmelCase__ (snake_case__ : list[list[int]] , snake_case__ : list[str] ): """simple docstring""" _snake_case : Any = [] _snake_case : Union[str, Any] = [0] * len(snake_case__ ) for i in range(len(chart[0] ) ): _snake_case : Tuple = 0 _snake_case : str = -1 for j in range(len(snake_case__ ) ): if chart[j][i] == 1: count += 1 _snake_case : Union[str, Any] = j if count == 1: _snake_case : Union[str, Any] = 1 for i in range(len(snake_case__ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case__ ) ): _snake_case : List[Any] = 0 temp.append(prime_implicants[i] ) while True: _snake_case : Optional[int] = 0 _snake_case : str = -1 _snake_case : Any = 0 for i in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _snake_case : Dict = count_n _snake_case : Dict = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case__ ) ): _snake_case : Optional[Any] = 0 def UpperCAmelCase__ (snake_case__ : list[str] , snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [[0 for x in range(len(snake_case__ ) )] for x in range(len(snake_case__ ) )] for i in range(len(snake_case__ ) ): _snake_case : Any = prime_implicants[i].count("""_""" ) for j in range(len(snake_case__ ) ): if is_for_table(prime_implicants[i] , binary[j] , snake_case__ ): _snake_case : Tuple = 1 return chart def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = int(input("""Enter the no. of variables\n""" ) ) _snake_case : List[str] = [ float(snake_case__ ) for x in input( """Enter the decimal representation of Minterms 'Spaces Separated'\n""" ).split() ] _snake_case : List[str] = decimal_to_binary(snake_case__ , snake_case__ ) _snake_case : str = check(snake_case__ ) print("""Prime Implicants are:""" ) print(snake_case__ ) _snake_case : int = prime_implicant_chart(snake_case__ , snake_case__ ) _snake_case : str = selection(snake_case__ , snake_case__ ) print("""Essential Prime Implicants are:""" ) print(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
64
1
"""simple docstring""" from math import pi def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ): """simple docstring""" return 2 * pi * radius * (angle / 3_60) if __name__ == "__main__": print(arc_length(90, 10))
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" stooge(snake_case__ , 0 , len(snake_case__ ) - 1 ) return arr def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int ): """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _snake_case , _snake_case : Tuple = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _snake_case : Dict = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case__ , i + t , (snake_case__) ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(stooge_sort(unsorted))
64
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase( metaclass=__a ): '''simple docstring''' lowercase__ = ["note_seq"] def __init__( self: Dict, *a_: Union[str, Any], **a_: List[str] ): '''simple docstring''' requires_backends(self, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Optional[int], *a_: Any, **a_: Optional[Any] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Tuple, *a_: Optional[Any], **a_: List[str] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] )
64
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase( metaclass=__a ): '''simple docstring''' lowercase__ = ["note_seq"] def __init__( self: Dict, *a_: Union[str, Any], **a_: List[str] ): '''simple docstring''' requires_backends(self, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Optional[int], *a_: Any, **a_: Optional[Any] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Tuple, *a_: Optional[Any], **a_: List[str] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] )
64
1
"""simple docstring""" A_ = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : int , snake_case__ : str , snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : Dict = [False] * len(snake_case__ ) _snake_case : str = [s] _snake_case : Tuple = True while queue: _snake_case : Union[str, Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(snake_case__ ) _snake_case : int = True _snake_case : str = u return visited[t] def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : List[str] , snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case : Dict = [-1] * (len(snake_case__ )) _snake_case : str = 0 _snake_case : Union[str, Any] = [] _snake_case : Optional[Any] = [i[:] for i in graph] # Record original cut, copy. while bfs(snake_case__ , snake_case__ , snake_case__ , snake_case__ ): _snake_case : List[str] = float("""Inf""" ) _snake_case : Optional[int] = sink while s != source: # Find the minimum value in select path _snake_case : Any = min(snake_case__ , graph[parent[s]][s] ) _snake_case : Optional[Any] = parent[s] max_flow += path_flow _snake_case : int = sink while v != source: _snake_case : Union[str, Any] = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _snake_case : Optional[Any] = parent[v] for i in range(len(snake_case__ ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
64
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : int = data _snake_case : Dict = [0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def UpperCamelCase_ ( a_: Optional[Any], a_: Dict ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xffffffff def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) _snake_case : Optional[int] = self.data + padding + struct.pack(""">Q""", 8 * len(self.data ) ) return padded_data def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def UpperCamelCase_ ( self: Optional[Any], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = list(struct.unpack(""">16L""", a_ ) ) + [0] * 64 for i in range(16, 80 ): _snake_case : List[Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = self.padding() _snake_case : str = self.split_blocks() for block in self.blocks: _snake_case : Any = self.expand_block(a_ ) _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = self.h for i in range(0, 80 ): if 0 <= i < 20: _snake_case : int = (b & c) | ((~b) & d) _snake_case : str = 0X5a827999 elif 20 <= i < 40: _snake_case : Optional[int] = b ^ c ^ d _snake_case : str = 0X6ed9eba1 elif 40 <= i < 60: _snake_case : List[Any] = (b & c) | (b & d) | (c & d) _snake_case : List[Any] = 0X8f1bbcdc elif 60 <= i < 80: _snake_case : List[Any] = b ^ c ^ d _snake_case : int = 0Xca62c1d6 _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = ( self.rotate(a_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(a_, 30 ), c, d, ) _snake_case : Union[str, Any] = ( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = B"""Test String""" assert SHAaHash(snake_case__ ).final_hash() == hashlib.shaa(snake_case__ ).hexdigest() # noqa: S324 def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _snake_case : Union[str, Any] = parser.parse_args() _snake_case : List[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _snake_case : str = f.read() else: _snake_case : int = bytes(snake_case__ , """utf-8""" ) print(SHAaHash(snake_case__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
64
1
"""simple docstring""" from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" if not is_accelerate_available(): return method _snake_case : Union[str, Any] = version.parse(accelerate.__version__ ).base_version if version.parse(snake_case__ ) < version.parse("""0.17.0""" ): return method def wrapper(self : Union[str, Any] , *snake_case__ : List[Any] , **snake_case__ : str ): if hasattr(self , """_hf_hook""" ) and hasattr(self._hf_hook , """pre_forward""" ): self._hf_hook.pre_forward(self ) return method(self , *snake_case__ , **snake_case__ ) return wrapper
64
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings A_ = r''' [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: title_sep (`str`, *optional*, defaults to `" / "`): Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`]. doc_sep (`str`, *optional*, defaults to `" // "`): Separator inserted between the text of the retrieved document and the original input when calling [`RagRetriever`]. n_docs (`int`, *optional*, defaults to 5): Number of documents to retrieve. max_combined_length (`int`, *optional*, defaults to 300): Max length of contextualized input returned by [`~RagRetriever.__call__`]. retrieval_vector_size (`int`, *optional*, defaults to 768): Dimensionality of the document embeddings indexed by [`RagRetriever`]. retrieval_batch_size (`int`, *optional*, defaults to 8): Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated [`RagRetriever`]. dataset (`str`, *optional*, defaults to `"wiki_dpr"`): A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids using `datasets.list_datasets()`). dataset_split (`str`, *optional*, defaults to `"train"`) Which split of the `dataset` to load. index_name (`str`, *optional*, defaults to `"compressed"`) The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and `"compressed"`. index_path (`str`, *optional*) The path to the serialized faiss index on disk. passages_path (`str`, *optional*): A path to text passages compatible with the faiss index. Required if using [`~models.rag.retrieval_rag.LegacyIndex`] use_dummy_dataset (`bool`, *optional*, defaults to `False`) Whether to load a "dummy" variant of the dataset specified by `dataset`. label_smoothing (`float`, *optional*, defaults to 0.0): Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed. do_marginalize (`bool`, *optional*, defaults to `False`): If `True`, the logits are marginalized over all documents by making use of `torch.nn.functional.log_softmax`. reduce_loss (`bool`, *optional*, defaults to `False`): Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation. do_deduplication (`bool`, *optional*, defaults to `True`): Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to `False` if used while training with distributed backend. exclude_bos_score (`bool`, *optional*, defaults to `False`): Whether or not to disregard the BOS token when computing the loss. output_retrieved(`bool`, *optional*, defaults to `False`): If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and `context_attention_mask` are returned. See returned tensors for more detail. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). forced_eos_token_id (`int`, *optional*): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`. ''' @add_start_docstrings(__a ) class lowercase( __a ): '''simple docstring''' lowercase__ = "rag" lowercase__ = True def __init__( self: Union[str, Any], a_: int=None, a_: Tuple=True, a_: Optional[int]=None, a_: List[str]=None, a_: int=None, a_: Optional[Any]=None, a_: List[str]=None, a_: Optional[Any]=" / ", a_: Tuple=" // ", a_: List[Any]=5, a_: Dict=300, a_: Tuple=768, a_: Optional[Any]=8, a_: int="wiki_dpr", a_: Any="train", a_: Optional[int]="compressed", a_: Optional[int]=None, a_: List[Any]=None, a_: Optional[Any]=False, a_: str=False, a_: Dict=0.0, a_: Union[str, Any]=True, a_: Union[str, Any]=False, a_: str=False, a_: List[str]=False, a_: Union[str, Any]=True, a_: Any=None, **a_: List[Any], ): '''simple docstring''' super().__init__( bos_token_id=a_, pad_token_id=a_, eos_token_id=a_, decoder_start_token_id=a_, forced_eos_token_id=a_, is_encoder_decoder=a_, prefix=a_, vocab_size=a_, **a_, ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _snake_case : Union[str, Any] = kwargs.pop("""question_encoder""" ) _snake_case : List[str] = question_encoder_config.pop("""model_type""" ) _snake_case : Union[str, Any] = kwargs.pop("""generator""" ) _snake_case : Any = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig _snake_case : Union[str, Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Optional[Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Any = reduce_loss _snake_case : Optional[int] = label_smoothing _snake_case : Dict = exclude_bos_score _snake_case : int = do_marginalize _snake_case : Optional[Any] = title_sep _snake_case : Any = doc_sep _snake_case : List[str] = n_docs _snake_case : Tuple = max_combined_length _snake_case : Optional[Any] = dataset _snake_case : Union[str, Any] = dataset_split _snake_case : Tuple = index_name _snake_case : Any = retrieval_vector_size _snake_case : Union[str, Any] = retrieval_batch_size _snake_case : str = passages_path _snake_case : Tuple = index_path _snake_case : List[Any] = use_dummy_dataset _snake_case : Optional[Any] = output_retrieved _snake_case : Tuple = do_deduplication _snake_case : Union[str, Any] = use_cache if self.forced_eos_token_id is None: _snake_case : Dict = getattr(self.generator, """forced_eos_token_id""", a_ ) @classmethod def UpperCamelCase_ ( cls: Any, a_: PretrainedConfig, a_: PretrainedConfig, **a_: Optional[Any] ): '''simple docstring''' return cls(question_encoder=question_encoder_config.to_dict(), generator=generator_config.to_dict(), **a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Optional[int] = copy.deepcopy(self.__dict__ ) _snake_case : List[str] = self.question_encoder.to_dict() _snake_case : Tuple = self.generator.to_dict() _snake_case : Dict = self.__class__.model_type return output
64
1
"""simple docstring""" import qiskit def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ): """simple docstring""" _snake_case : Optional[int] = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register _snake_case : Union[str, Any] = qiskit.QuantumCircuit(snake_case__ , snake_case__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator _snake_case : Optional[int] = qiskit.execute(snake_case__ , snake_case__ , shots=10_00 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(snake_case__ ) if __name__ == "__main__": print(F'''Total count for various states are: {single_qubit_measure(1, 1)}''')
64
"""simple docstring""" import os from typing import Dict, List, Tuple, TypeVar, Union A_ = TypeVar('''T''') A_ = Union[List[T], Tuple[T, ...]] A_ = Union[T, List[T], Dict[str, T]] A_ = Union[str, bytes, os.PathLike]
64
1
"""simple docstring""" from __future__ import annotations A_ = '''Muhammad Umer Farooq''' A_ = '''MIT''' A_ = '''1.0.0''' A_ = '''Muhammad Umer Farooq''' A_ = '''contact@muhammadumerfarooq.me''' A_ = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class lowercase( __a ): '''simple docstring''' def __init__( self: Optional[Any], a_: str ): '''simple docstring''' super().__init__() _snake_case : list[str] = [] _snake_case : List[Any] = domain def UpperCamelCase_ ( self: List[Any], a_: str, a_: list[tuple[str, str | None]] ): '''simple docstring''' if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: _snake_case : Any = parse.urljoin(self.domain, a_ ) self.urls.append(a_ ) def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" return ".".join(get_sub_domain_name(snake_case__ ).split(""".""" )[-2:] ) def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" return parse.urlparse(snake_case__ ).netloc def UpperCAmelCase__ (snake_case__ : str = "https://github.com" ): """simple docstring""" _snake_case : Dict = get_domain_name(snake_case__ ) # Initialize the parser _snake_case : List[str] = Parser(snake_case__ ) try: # Open URL _snake_case : Union[str, Any] = requests.get(snake_case__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through _snake_case : str = set() for link in parser.urls: # open URL. # read = requests.get(link) try: _snake_case : Optional[Any] = requests.get(snake_case__ ) # Get the valid email. _snake_case : Tuple = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(snake_case__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(snake_case__ ) if __name__ == "__main__": A_ = emails_from_url('''https://github.com''') print(F'''{len(emails)} emails found:''') print('''\n'''.join(sorted(emails)))
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] _snake_case : List[Any] = [] def generate(snake_case__ : int , snake_case__ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even _snake_case , _snake_case : Optional[Any] = arr[k - 1], arr[i] else: # k is odd _snake_case , _snake_case : List[str] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
64
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig class lowercase( __a ): '''simple docstring''' lowercase__ = "bert-generation" def __init__( self: str, a_: str=50_358, a_: List[Any]=1_024, a_: Union[str, Any]=24, a_: int=16, a_: Union[str, Any]=4_096, a_: Union[str, Any]="gelu", a_: Tuple=0.1, a_: Any=0.1, a_: Union[str, Any]=512, a_: List[str]=0.02, a_: List[str]=1E-12, a_: Union[str, Any]=0, a_: Union[str, Any]=2, a_: List[Any]=1, a_: int="absolute", a_: Dict=True, **a_: List[Any], ): '''simple docstring''' super().__init__(pad_token_id=a_, bos_token_id=a_, eos_token_id=a_, **a_ ) _snake_case : Optional[int] = vocab_size _snake_case : List[Any] = hidden_size _snake_case : str = num_hidden_layers _snake_case : Tuple = num_attention_heads _snake_case : Union[str, Any] = hidden_act _snake_case : Optional[Any] = intermediate_size _snake_case : Tuple = hidden_dropout_prob _snake_case : int = attention_probs_dropout_prob _snake_case : Any = max_position_embeddings _snake_case : List[str] = initializer_range _snake_case : Optional[Any] = layer_norm_eps _snake_case : List[Any] = position_embedding_type _snake_case : Tuple = use_cache
64
"""simple docstring""" from math import factorial A_ = {str(d): factorial(d) for d in range(10)} def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , snake_case__ ) if sum_of_digit_factorial(snake_case__ ) == i ) if __name__ == "__main__": print(F'''{solution() = }''')
64
1
"""simple docstring""" A_ = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} A_ = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def UpperCAmelCase__ (snake_case__ : dict[int, list[int]] , snake_case__ : int , snake_case__ : list[bool] ): """simple docstring""" _snake_case : Union[str, Any] = True _snake_case : List[Any] = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(snake_case__ , snake_case__ , snake_case__ ) order.append(snake_case__ ) return order def UpperCAmelCase__ (snake_case__ : dict[int, list[int]] , snake_case__ : int , snake_case__ : list[bool] ): """simple docstring""" _snake_case : Dict = True _snake_case : Dict = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(snake_case__ , snake_case__ , snake_case__ ) return component def UpperCAmelCase__ (snake_case__ : dict[int, list[int]] ): """simple docstring""" _snake_case : Any = len(snake_case__ ) * [False] _snake_case : dict[int, list[int]] = {vert: [] for vert in range(len(snake_case__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(snake_case__ ) _snake_case : Optional[Any] = [] for i, was_visited in enumerate(snake_case__ ): if not was_visited: order += topology_sort(snake_case__ , snake_case__ , snake_case__ ) _snake_case : int = [] _snake_case : Dict = len(snake_case__ ) * [False] for i in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = order[len(snake_case__ ) - i - 1] if not visited[vert]: _snake_case : Tuple = find_components(snake_case__ , snake_case__ , snake_case__ ) components_list.append(snake_case__ ) return components_list
64
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : int ): """simple docstring""" if len(snake_case__ ) < k or k < 0: raise ValueError("""Invalid Input""" ) _snake_case : Optional[int] = sum(array[:k] ) for i in range(len(snake_case__ ) - k ): _snake_case : Optional[Any] = current_sum - array[i] + array[i + k] _snake_case : List[str] = max(snake_case__ , snake_case__ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() A_ = [randint(-10_00, 10_00) for i in range(1_00)] A_ = randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
64
1
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging A_ = logging.get_logger(__name__) A_ = { '''Visual-Attention-Network/van-base''': ( '''https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json''' ), } class lowercase( __a ): '''simple docstring''' lowercase__ = "van" def __init__( self: List[Any], a_: Dict=224, a_: int=3, a_: List[Any]=[7, 3, 3, 3], a_: List[Any]=[4, 2, 2, 2], a_: Optional[int]=[64, 128, 320, 512], a_: Tuple=[3, 3, 12, 3], a_: List[str]=[8, 8, 4, 4], a_: Dict="gelu", a_: Any=0.02, a_: List[str]=1E-6, a_: Union[str, Any]=1E-2, a_: Union[str, Any]=0.0, a_: List[Any]=0.0, **a_: str, ): '''simple docstring''' super().__init__(**a_ ) _snake_case : Any = image_size _snake_case : List[str] = num_channels _snake_case : Tuple = patch_sizes _snake_case : Tuple = strides _snake_case : List[str] = hidden_sizes _snake_case : Optional[int] = depths _snake_case : Optional[int] = mlp_ratios _snake_case : int = hidden_act _snake_case : Any = initializer_range _snake_case : Any = layer_norm_eps _snake_case : Dict = layer_scale_init_value _snake_case : List[Any] = drop_path_rate _snake_case : int = dropout_rate
64
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } A_ = { '''yjernite/retribert-base-uncased''': 5_12, } A_ = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = RetriBertTokenizer lowercase__ = ["input_ids", "attention_mask"] def __init__( self: int, a_: int=None, a_: Dict=None, a_: Any=True, a_: int="[UNK]", a_: Any="[SEP]", a_: List[Any]="[PAD]", a_: List[Any]="[CLS]", a_: str="[MASK]", a_: Dict=True, a_: Optional[int]=None, **a_: Tuple, ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Dict = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : List[Any] = do_lower_case _snake_case : List[str] = strip_accents _snake_case : Tuple = tokenize_chinese_chars _snake_case : Tuple = normalizer_class(**a_ ) _snake_case : List[str] = do_lower_case def UpperCamelCase_ ( self: Any, a_: str, a_: Optional[int]=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: List[str], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: Dict, a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : Union[str, Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
1
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''', }, '''merges_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''Salesforce/codegen-350M-mono''': ( '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json''' ), }, } A_ = { '''Salesforce/codegen-350M-mono''': 20_48, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] lowercase__ = CodeGenTokenizer def __init__( self: Union[str, Any], a_: List[Any]=None, a_: str=None, a_: str=None, a_: Dict="<|endoftext|>", a_: Tuple="<|endoftext|>", a_: str="<|endoftext|>", a_: List[Any]=False, **a_: List[str], ): '''simple docstring''' super().__init__( a_, a_, tokenizer_file=a_, unk_token=a_, bos_token=a_, eos_token=a_, add_prefix_space=a_, **a_, ) if kwargs.pop("""add_bos_token""", a_ ): _snake_case : str = kwargs.pop("""name_or_path""", """""" ) raise ValueError( """Currenty GPT2's fast tokenizer does NOT support adding a BOS token.""" """Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n""" f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n" f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n" """This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.""" """ so that the fast tokenizer works correctly.""" ) _snake_case : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : Dict = getattr(a_, pre_tok_state.pop("""type""" ) ) _snake_case : Dict = add_prefix_space _snake_case : str = pre_tok_class(**a_ ) _snake_case : List[Any] = add_prefix_space def UpperCamelCase_ ( self: Any, *a_: Any, **a_: int ): '''simple docstring''' _snake_case : Optional[int] = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], *a_: Any, **a_: List[str] ): '''simple docstring''' _snake_case : Dict = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : List[Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ ) def UpperCamelCase_ ( self: str, a_: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], a_: bool = False, a_: bool = None, a_: Optional[List[str]] = None, **a_: List[str], ): '''simple docstring''' _snake_case : Any = super().decode( token_ids=a_, skip_special_tokens=a_, clean_up_tokenization_spaces=a_, **a_, ) if truncate_before_pattern is not None and len(a_ ) > 0: _snake_case : List[str] = self.truncate(a_, a_ ) return decoded_text def UpperCamelCase_ ( self: Dict, a_: Tuple, a_: Optional[Any] ): '''simple docstring''' def find_re(a_: Dict, a_: str, a_: Union[str, Any] ): _snake_case : Any = pattern.search(a_, a_ ) return m.start() if m else -1 _snake_case : Tuple = [re.compile(a_, re.MULTILINE ) for pattern in truncate_before_pattern] _snake_case : List[Any] = list(re.finditer("""^print""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : int = completion[: prints[1].start()] _snake_case : List[str] = list(re.finditer("""^def""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : List[Any] = completion[: defs[1].start()] _snake_case : int = 0 _snake_case : List[Any] = [ pos for pos in [find_re(a_, a_, a_ ) for terminal in terminals] if pos != -1 ] if len(a_ ) > 0: return completion[: min(a_ )] else: return completion
64
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CodeGenTokenizer lowercase__ = CodeGenTokenizerFast lowercase__ = True lowercase__ = {"add_prefix_space": True} lowercase__ = False def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _snake_case : Tuple = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] _snake_case : Tuple = dict(zip(a_, range(len(a_ ) ) ) ) _snake_case : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _snake_case : List[Any] = {"""unk_token""": """<unk>"""} _snake_case : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) _snake_case : Optional[Any] = 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(a_ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(a_ ) ) def UpperCamelCase_ ( self: Any, **a_: int ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Any, **a_: str ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Dict ): '''simple docstring''' _snake_case : Union[str, Any] = """lower newer""" _snake_case : Tuple = """lower newer""" return input_text, output_text def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) _snake_case : Optional[Any] = """lower newer""" _snake_case : Optional[int] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] _snake_case : int = tokenizer.tokenize(a_, add_prefix_space=a_ ) self.assertListEqual(a_, a_ ) _snake_case : str = tokens + [tokenizer.unk_token] _snake_case : Optional[int] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : int = self.get_tokenizer() _snake_case : int = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : Dict = """lower newer""" # Testing tokenization _snake_case : Dict = tokenizer.tokenize(a_, add_prefix_space=a_ ) _snake_case : List[str] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids without special tokens _snake_case : Optional[Any] = tokenizer.encode(a_, add_special_tokens=a_, add_prefix_space=a_ ) _snake_case : Tuple = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids with special tokens _snake_case : Tuple = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : int = tokenizer.encode(a_, add_prefix_space=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) # Testing the unknown token _snake_case : Tuple = tokens + [rust_tokenizer.unk_token] _snake_case : List[Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Dict, *a_: Dict, **a_: int ): '''simple docstring''' pass def UpperCamelCase_ ( self: int, a_: List[Any]=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : List[Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) # Simple input _snake_case : Any = """This is a simple input""" _snake_case : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Optional[int] = ("""This is a simple input""", """This is a pair""") _snake_case : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) # Pair input self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token="""<pad>""" ) # Simple input _snake_case : List[Any] = """This is a simple input""" _snake_case : int = ["""This is a simple input looooooooong""", """This is a simple input"""] _snake_case : Any = ("""This is a simple input""", """This is a pair""") _snake_case : str = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] _snake_case : str = tokenizer.pad_token_id _snake_case : Optional[int] = tokenizer(a_, padding="""max_length""", max_length=30, return_tensors="""np""" ) _snake_case : Dict = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) _snake_case : Tuple = tokenizer(*a_, padding="""max_length""", max_length=60, return_tensors="""np""" ) _snake_case : Optional[Any] = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Tuple = """$$$""" _snake_case : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=a_, add_bos_token=a_ ) _snake_case : str = """This is a simple input""" _snake_case : int = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Tuple = tokenizer(a_ ) _snake_case : Optional[Any] = tokenizer(a_ ) self.assertEqual(out_s.input_ids[0], a_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) _snake_case : Optional[int] = tokenizer.decode(out_s.input_ids ) _snake_case : int = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], a_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) _snake_case : Dict = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" _snake_case : Union[str, Any] = """\nif len_a > len_b: result = a\nelse: result = b""" _snake_case : Optional[Any] = tokenizer.encode(a_ ) _snake_case : Dict = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] _snake_case : Optional[Any] = tokenizer.decode(a_, truncate_before_pattern=a_ ) self.assertEqual(a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' pass
64
1
"""simple docstring""" import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() A_ = logging.get_logger(__name__) A_ = '''Hello world! cécé herlolip''' def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : bool ): """simple docstring""" _snake_case : Dict = FairseqRobertaModel.from_pretrained(snake_case__ ) roberta.eval() # disable dropout _snake_case : Union[str, Any] = roberta.model.encoder.sentence_encoder _snake_case : Optional[int] = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1e-5 , ) if classification_head: _snake_case : Optional[int] = roberta.model.classification_heads["""mnli"""].out_proj.weight.shape[0] print("""Our RoBERTa config:""" , snake_case__ ) _snake_case : Any = XLMRobertaXLForSequenceClassification(snake_case__ ) if classification_head else XLMRobertaXLForMaskedLM(snake_case__ ) model.eval() # Now let's copy all the weights. # Embeddings _snake_case : str = roberta_sent_encoder.embed_tokens.weight _snake_case : Union[str, Any] = roberta_sent_encoder.embed_positions.weight _snake_case : str = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. _snake_case : Any = roberta_sent_encoder.layer_norm.weight _snake_case : List[Any] = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer _snake_case : BertLayer = model.roberta.encoder.layer[i] _snake_case : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] _snake_case : RobertaAttention = layer.attention _snake_case : Any = roberta_layer.self_attn_layer_norm.weight _snake_case : List[str] = roberta_layer.self_attn_layer_norm.bias # self attention _snake_case : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) _snake_case : int = roberta_layer.self_attn.q_proj.weight _snake_case : int = roberta_layer.self_attn.q_proj.bias _snake_case : Dict = roberta_layer.self_attn.k_proj.weight _snake_case : Union[str, Any] = roberta_layer.self_attn.k_proj.bias _snake_case : Any = roberta_layer.self_attn.v_proj.weight _snake_case : int = roberta_layer.self_attn.v_proj.bias # self-attention output _snake_case : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape _snake_case : Dict = roberta_layer.self_attn.out_proj.weight _snake_case : Dict = roberta_layer.self_attn.out_proj.bias # this one is final layer norm _snake_case : Union[str, Any] = roberta_layer.final_layer_norm.weight _snake_case : Optional[int] = roberta_layer.final_layer_norm.bias # intermediate _snake_case : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape _snake_case : Tuple = roberta_layer.fca.weight _snake_case : Optional[Any] = roberta_layer.fca.bias # output _snake_case : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape _snake_case : Optional[int] = roberta_layer.fca.weight _snake_case : Tuple = roberta_layer.fca.bias # end of layer if classification_head: _snake_case : str = roberta.model.classification_heads["""mnli"""].dense.weight _snake_case : Optional[Any] = roberta.model.classification_heads["""mnli"""].dense.bias _snake_case : Optional[int] = roberta.model.classification_heads["""mnli"""].out_proj.weight _snake_case : Optional[int] = roberta.model.classification_heads["""mnli"""].out_proj.bias else: # LM Head _snake_case : List[Any] = roberta.model.encoder.lm_head.dense.weight _snake_case : Dict = roberta.model.encoder.lm_head.dense.bias _snake_case : Any = roberta.model.encoder.lm_head.layer_norm.weight _snake_case : Dict = roberta.model.encoder.lm_head.layer_norm.bias _snake_case : Dict = roberta.model.encoder.lm_head.weight _snake_case : str = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. _snake_case : torch.Tensor = roberta.encode(snake_case__ ).unsqueeze(0 ) # batch of size 1 _snake_case : int = model(snake_case__ )[0] if classification_head: _snake_case : Optional[Any] = roberta.model.classification_heads["""mnli"""](roberta.extract_features(snake_case__ ) ) else: _snake_case : Optional[int] = roberta.model(snake_case__ )[0] print(our_output.shape , their_output.shape ) _snake_case : List[str] = torch.max(torch.abs(our_output - their_output ) ).item() print(F"max_absolute_diff = {max_absolute_diff}" ) # ~ 1e-7 _snake_case : Any = torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print("""Do both models output the same tensors?""" , """🔥""" if success else """💩""" ) if not success: raise Exception("""Something went wRoNg""" ) pathlib.Path(snake_case__ ).mkdir(parents=snake_case__ , exist_ok=snake_case__ ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) A_ = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
64
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser A_ = re.compile(r'''\s+''') def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" return {"hash": hashlib.mda(re.sub(snake_case__ , """""" , example["""content"""] ).encode("""utf-8""" ) ).hexdigest()} def UpperCAmelCase__ (snake_case__ : Dict ): """simple docstring""" _snake_case : Any = [len(snake_case__ ) for line in example["""content"""].splitlines()] return {"line_mean": np.mean(snake_case__ ), "line_max": max(snake_case__ )} def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" _snake_case : Tuple = np.mean([c.isalnum() for c in example["""content"""]] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : List[Any] ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example["""hash"""] ) return True else: return False def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : List[str]=5 ): """simple docstring""" _snake_case : Any = ["""auto-generated""", """autogenerated""", """automatically generated"""] _snake_case : Tuple = example["""content"""].splitlines() for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Union[str, Any]=5 , snake_case__ : Any=0.05 ): """simple docstring""" _snake_case : Optional[Any] = ["""unit tests""", """test file""", """configuration file"""] _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : Dict = 0 _snake_case : str = 0 # first test for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _snake_case : Optional[int] = example["""content"""].count("""\n""" ) _snake_case : Tuple = int(coeff * nlines ) for line in lines: count_config += line.lower().count("""config""" ) count_test += line.lower().count("""test""" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Optional[int] = ["""def """, """class """, """for """, """while """] _snake_case : str = example["""content"""].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : List[str]=4 ): """simple docstring""" _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : str = 0 for line in lines: counter += line.lower().count("""=""" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase__ (snake_case__ : List[str] ): """simple docstring""" _snake_case : Optional[Any] = tokenizer(example["""content"""] , truncation=snake_case__ )["""input_ids"""] _snake_case : Optional[Any] = len(example["""content"""] ) / len(snake_case__ ) return {"ratio": ratio} def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[int] = {} results.update(get_hash(snake_case__ ) ) results.update(line_stats(snake_case__ ) ) results.update(alpha_stats(snake_case__ ) ) results.update(char_token_ratio(snake_case__ ) ) results.update(is_autogenerated(snake_case__ ) ) results.update(is_config_or_test(snake_case__ ) ) results.update(has_no_keywords(snake_case__ ) ) results.update(has_few_assignments(snake_case__ ) ) return results def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : List[str] ): """simple docstring""" if not check_uniques(snake_case__ , snake_case__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" with open(snake_case__ , """rb""" ) as f_in: with gzip.open(str(snake_case__ ) + """.gz""" , """wb""" , compresslevel=6 ) as f_out: shutil.copyfileobj(snake_case__ , snake_case__ ) os.unlink(snake_case__ ) # Settings A_ = HfArgumentParser(PreprocessingArguments) A_ = parser.parse_args() if args.num_workers is None: A_ = multiprocessing.cpu_count() A_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset A_ = time.time() A_ = load_dataset(args.dataset_name, split='''train''') print(F'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing A_ = time.time() A_ = ds.map(preprocess, num_proc=args.num_workers) print(F'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes A_ = set(ds.unique('''hash''')) A_ = len(uniques) / len(ds) print(F'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics A_ = time.time() A_ = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F'''Time to filter dataset: {time.time()-t_start:.2f}''') print(F'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: A_ = time.time() A_ , A_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(F'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file A_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) A_ = output_dir / '''data''' data_dir.mkdir(exist_ok=True) A_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): A_ = str(data_dir / F'''file-{file_number+1:012}.json''') A_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'''Time to save dataset: {time.time()-t_start:.2f}''')
64
1
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser A_ = re.compile(r'''\s+''') def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" return {"hash": hashlib.mda(re.sub(snake_case__ , """""" , example["""content"""] ).encode("""utf-8""" ) ).hexdigest()} def UpperCAmelCase__ (snake_case__ : Dict ): """simple docstring""" _snake_case : Any = [len(snake_case__ ) for line in example["""content"""].splitlines()] return {"line_mean": np.mean(snake_case__ ), "line_max": max(snake_case__ )} def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" _snake_case : Tuple = np.mean([c.isalnum() for c in example["""content"""]] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : List[Any] ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example["""hash"""] ) return True else: return False def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : List[str]=5 ): """simple docstring""" _snake_case : Any = ["""auto-generated""", """autogenerated""", """automatically generated"""] _snake_case : Tuple = example["""content"""].splitlines() for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Union[str, Any]=5 , snake_case__ : Any=0.05 ): """simple docstring""" _snake_case : Optional[Any] = ["""unit tests""", """test file""", """configuration file"""] _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : Dict = 0 _snake_case : str = 0 # first test for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _snake_case : Optional[int] = example["""content"""].count("""\n""" ) _snake_case : Tuple = int(coeff * nlines ) for line in lines: count_config += line.lower().count("""config""" ) count_test += line.lower().count("""test""" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Optional[int] = ["""def """, """class """, """for """, """while """] _snake_case : str = example["""content"""].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : List[str]=4 ): """simple docstring""" _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : str = 0 for line in lines: counter += line.lower().count("""=""" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase__ (snake_case__ : List[str] ): """simple docstring""" _snake_case : Optional[Any] = tokenizer(example["""content"""] , truncation=snake_case__ )["""input_ids"""] _snake_case : Optional[Any] = len(example["""content"""] ) / len(snake_case__ ) return {"ratio": ratio} def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[int] = {} results.update(get_hash(snake_case__ ) ) results.update(line_stats(snake_case__ ) ) results.update(alpha_stats(snake_case__ ) ) results.update(char_token_ratio(snake_case__ ) ) results.update(is_autogenerated(snake_case__ ) ) results.update(is_config_or_test(snake_case__ ) ) results.update(has_no_keywords(snake_case__ ) ) results.update(has_few_assignments(snake_case__ ) ) return results def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : List[str] ): """simple docstring""" if not check_uniques(snake_case__ , snake_case__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" with open(snake_case__ , """rb""" ) as f_in: with gzip.open(str(snake_case__ ) + """.gz""" , """wb""" , compresslevel=6 ) as f_out: shutil.copyfileobj(snake_case__ , snake_case__ ) os.unlink(snake_case__ ) # Settings A_ = HfArgumentParser(PreprocessingArguments) A_ = parser.parse_args() if args.num_workers is None: A_ = multiprocessing.cpu_count() A_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset A_ = time.time() A_ = load_dataset(args.dataset_name, split='''train''') print(F'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing A_ = time.time() A_ = ds.map(preprocess, num_proc=args.num_workers) print(F'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes A_ = set(ds.unique('''hash''')) A_ = len(uniques) / len(ds) print(F'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics A_ = time.time() A_ = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F'''Time to filter dataset: {time.time()-t_start:.2f}''') print(F'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: A_ = time.time() A_ , A_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(F'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file A_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) A_ = output_dir / '''data''' data_dir.mkdir(exist_ok=True) A_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): A_ = str(data_dir / F'''file-{file_number+1:012}.json''') A_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'''Time to save dataset: {time.time()-t_start:.2f}''')
64
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase( unittest.TestCase ): '''simple docstring''' @property def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Any = ort.SessionOptions() _snake_case : Union[str, Any] = False return options def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _snake_case : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _snake_case : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _snake_case : Optional[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""", revision="""onnx""", safety_checker=a_, feature_extractor=a_, provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : Optional[Any] = """A red cat sitting on a park bench""" _snake_case : Optional[int] = np.random.RandomState(0 ) _snake_case : Any = pipe( prompt=a_, image=a_, mask_image=a_, strength=0.75, guidance_scale=7.5, num_inference_steps=15, generator=a_, output_type="""np""", ) _snake_case : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
64
1
"""simple docstring""" from __future__ import annotations from statistics import mean def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : list[int] , snake_case__ : int ): """simple docstring""" _snake_case : List[str] = [0] * no_of_processes _snake_case : Union[str, Any] = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(snake_case__ ): _snake_case : str = burst_time[i] _snake_case : list[int] = [] _snake_case : Dict = 0 _snake_case : int = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: _snake_case : Any = [] _snake_case : Tuple = -1 for i in range(snake_case__ ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(snake_case__ ) if len(snake_case__ ) > 0: _snake_case : List[str] = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: _snake_case : int = i total_time += burst_time[target_process] completed += 1 _snake_case : List[str] = 0 _snake_case : List[str] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : int , snake_case__ : list[int] ): """simple docstring""" _snake_case : Dict = [0] * no_of_processes for i in range(snake_case__ ): _snake_case : str = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print('''[TEST CASE 01]''') A_ = 4 A_ = [2, 5, 3, 7] A_ = [0, 0, 0, 0] A_ = calculate_waitingtime(arrival_time, burst_time, no_of_processes) A_ = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print('''PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time''') for i, process_id in enumerate(list(range(1, 5))): print( F'''{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t''' F'''{waiting_time[i]}\t\t\t\t{turn_around_time[i]}''' ) print(F'''\nAverage waiting time = {mean(waiting_time):.5f}''') print(F'''Average turnaround time = {mean(turn_around_time):.5f}''')
64
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() A_ = logging.get_logger(__name__) A_ = { '''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''', '''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''', } A_ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Dict , snake_case__ : Any , snake_case__ : str , snake_case__ : str ): """simple docstring""" for attribute in key.split(""".""" ): _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ) if weight_type is not None: _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ).shape else: _snake_case : Optional[Any] = hf_pointer.shape assert hf_shape == value.shape, ( 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": _snake_case : int = value elif weight_type == "weight_g": _snake_case : str = value elif weight_type == "weight_v": _snake_case : Tuple = value elif weight_type == "bias": _snake_case : List[str] = value else: _snake_case : int = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str] ): """simple docstring""" _snake_case : List[Any] = [] _snake_case : Optional[Any] = fairseq_model.state_dict() _snake_case : str = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _snake_case : Optional[Any] = None for name, value in fairseq_dict.items(): _snake_case : Optional[Any] = False if "conv_layers" in name: load_conv_layer( snake_case__ , snake_case__ , snake_case__ , snake_case__ , hf_model.config.feat_extract_norm == """group""" , ) _snake_case : Dict = True elif name.split(""".""" )[0] == "proj": _snake_case : Dict = fairseq_model.proj _snake_case : Optional[int] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _snake_case : Dict = True if "*" in mapped_key: _snake_case : Optional[int] = name.split(snake_case__ )[0].split(""".""" )[-2] _snake_case : Union[str, Any] = mapped_key.replace("""*""" , snake_case__ ) if "weight_g" in name: _snake_case : str = """weight_g""" elif "weight_v" in name: _snake_case : Optional[Any] = """weight_v""" elif "bias" in name: _snake_case : Union[str, Any] = """bias""" elif "weight" in name: _snake_case : int = """weight""" else: _snake_case : Optional[int] = None set_recursively(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) continue if not is_used: unused_weights.append(snake_case__ ) logger.warning(F"Unused weights: {unused_weights}" ) return proj_weight def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : int ): """simple docstring""" _snake_case : Any = full_name.split("""conv_layers.""" )[-1] _snake_case : Optional[int] = name.split(""".""" ) _snake_case : List[str] = int(items[0] ) _snake_case : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _snake_case : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _snake_case : List[Any] = 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _snake_case : int = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _snake_case : List[str] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case , _snake_case : Optional[Any] = emb.weight.shape _snake_case : Optional[int] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _snake_case : Union[str, Any] = emb.weight.data return lin_layer def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" with open(snake_case__ , """r""" , encoding="""utf-8""" ) as f: _snake_case : Any = f.readlines() _snake_case : Optional[Any] = [line.split(""" """ )[0] for line in lines] _snake_case : str = len(snake_case__ ) _snake_case : Tuple = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(snake_case__ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def UpperCAmelCase__ (snake_case__ : int , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Dict , snake_case__ : List[Any] , snake_case__ : str , snake_case__ : Union[str, Any] , ): """simple docstring""" _snake_case : Optional[int] = WavaVecaConfig.from_pretrained(snake_case__ ) _snake_case : List[str] = SpeechaTextaConfig.from_pretrained( snake_case__ , vocab_size=snake_case__ , decoder_layers=snake_case__ , do_stable_layer_norm=snake_case__ ) _snake_case : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case__ , return_attention_mask=snake_case__ , ) _snake_case , _snake_case , _snake_case : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) _snake_case : Optional[Any] = model[0].eval() # set weights for wav2vec2 encoder _snake_case : Any = WavaVecaModel(snake_case__ ) _snake_case : Optional[Any] = recursively_load_weights_wavaveca(model.encoder , snake_case__ ) _snake_case : Optional[Any] = SpeechaTextaForCausalLM(snake_case__ ) _snake_case , _snake_case : List[str] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case__ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) _snake_case : Any = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(F"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) _snake_case : Any = SpeechEncoderDecoderModel(encoder=snake_case__ , decoder=snake_case__ ) _snake_case : Any = False # add projection layer _snake_case : int = nn.Parameter(projection_layer.weight ) _snake_case : Any = nn.Parameter(projection_layer.bias ) _snake_case : Any = create_vocab_dict(snake_case__ ) with open(os.path.join(snake_case__ , """vocab.json""" ) , """w""" ) as fp: json.dump(snake_case__ , snake_case__ ) _snake_case : Dict = SpeechaTextaTokenizer(os.path.join(snake_case__ , """vocab.json""" ) ) tokenizer.save_pretrained(snake_case__ ) _snake_case : str = hf_wavavec.config.to_dict() _snake_case : List[str] = tokenizer.pad_token_id _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Union[str, Any] = tokenizer.eos_token_id _snake_case : Optional[Any] = """speech_to_text_2""" _snake_case : Optional[int] = """wav2vec2""" _snake_case : Tuple = SpeechEncoderDecoderConfig.from_dict(snake_case__ ) hf_wavavec.save_pretrained(snake_case__ ) feature_extractor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = 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( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=1_02_24, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') A_ = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
64
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowercase( __a ): '''simple docstring''' def __init__( self: str, a_: List[Any], a_: Optional[Any] ): '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM _snake_case : int = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=a_, scheduler=a_ ) @torch.no_grad() def __call__( self: Optional[int], a_: int = 1, a_: Optional[Union[torch.Generator, List[torch.Generator]]] = None, a_: float = 0.0, a_: int = 50, a_: Optional[bool] = None, a_: Optional[str] = "pil", a_: bool = True, ): '''simple docstring''' if isinstance(self.unet.config.sample_size, a_ ): _snake_case : Optional[Any] = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: _snake_case : Dict = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(a_, a_ ) and len(a_ ) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(a_ )}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) _snake_case : Dict = randn_tensor(a_, generator=a_, device=self.device, dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(a_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _snake_case : List[Any] = self.unet(a_, a_ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 _snake_case : Optional[int] = self.scheduler.step( a_, a_, a_, eta=a_, use_clipped_model_output=a_, generator=a_ ).prev_sample _snake_case : List[Any] = (image / 2 + 0.5).clamp(0, 1 ) _snake_case : Union[str, Any] = image.cpu().permute(0, 2, 3, 1 ).numpy() if output_type == "pil": _snake_case : str = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
64
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A_ = 16 A_ = 32 def UpperCAmelCase__ (snake_case__ : Accelerator , snake_case__ : int = 16 ): """simple docstring""" _snake_case : Optional[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _snake_case : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(snake_case__ : Any ): # max_length=None => use the model max length (it's actually the default) _snake_case : Any = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _snake_case : List[Any] = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case : int = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _snake_case : Optional[int] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _snake_case : str = 16 elif accelerator.mixed_precision != "no": _snake_case : Optional[int] = 8 else: _snake_case : Optional[int] = None return tokenizer.pad( snake_case__ , padding="""longest""" , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _snake_case : Optional[int] = DataLoader( tokenized_datasets["""train"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) _snake_case : Dict = DataLoader( tokenized_datasets["""validation"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders A_ = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any ): """simple docstring""" if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , snake_case__ ) == "1": _snake_case : List[Any] = 2 # Initialize accelerator _snake_case : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case : Tuple = config["""lr"""] _snake_case : str = int(config["""num_epochs"""] ) _snake_case : Union[str, Any] = int(config["""seed"""] ) _snake_case : Union[str, Any] = int(config["""batch_size"""] ) _snake_case : List[str] = evaluate.load("""glue""" , """mrpc""" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case__ ) def inner_training_loop(snake_case__ : Union[str, Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case : List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _snake_case : Tuple = model.to(accelerator.device ) # Instantiate optimizer _snake_case : str = AdamW(params=model.parameters() , lr=snake_case__ ) _snake_case , _snake_case : Optional[int] = get_dataloaders(snake_case__ , snake_case__ ) # Instantiate scheduler _snake_case : str = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=1_00 , num_training_steps=(len(snake_case__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : List[str] = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _snake_case : int = model(**snake_case__ ) _snake_case : str = outputs.loss accelerator.backward(snake_case__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _snake_case : int = model(**snake_case__ ) _snake_case : Optional[Any] = outputs.logits.argmax(dim=-1 ) _snake_case , _snake_case : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) _snake_case : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , snake_case__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=snake_case__ , default=snake_case__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _snake_case : Dict = parser.parse_args() _snake_case : int = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
64
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ): """simple docstring""" while b: _snake_case , _snake_case : Optional[int] = b, a % b return a def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ): """simple docstring""" return a if b == 0 else euclidean_gcd_recursive(snake_case__ , a % b ) def UpperCAmelCase__ (): """simple docstring""" print(F"euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}" ) print(F"euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}" ) print(F"euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}" ) print(F"euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}" ) print(F"euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}" ) print(F"euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}" ) print(F"euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}" ) print(F"euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}" ) print(F"euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}" ) print(F"euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}" ) if __name__ == "__main__": main()
64
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def UpperCAmelCase__ (snake_case__ : Optional[int] , snake_case__ : Any=7 ): """simple docstring""" _snake_case : Any = None if token is not None: _snake_case : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} # The id of a workflow (not of a workflow run) _snake_case : List[str] = """636036""" _snake_case : Union[str, Any] = F"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}" _snake_case : str = requests.get(snake_case__ , headers=snake_case__ ).json() return result["workflow_runs"] def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : str = get_daily_ci_runs(snake_case__ ) _snake_case : str = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _snake_case : List[str] = workflow_run["""id"""] break return workflow_run_id def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Union[str, Any] , snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[Any] = get_last_daily_ci_runs(snake_case__ ) if workflow_run_id is not None: _snake_case : Optional[Any] = get_artifacts_links(worflow_run_id=snake_case__ , token=snake_case__ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _snake_case : Optional[int] = artifacts_links[artifact_name] download_artifact( artifact_name=snake_case__ , artifact_url=snake_case__ , output_dir=snake_case__ , token=snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] , snake_case__ : List[str] , snake_case__ : int ): """simple docstring""" get_last_daily_ci_artifacts(snake_case__ , snake_case__ , snake_case__ ) _snake_case : int = {} for artifact_name in artifact_names: _snake_case : int = os.path.join(snake_case__ , F"{artifact_name}.zip" ) if os.path.isfile(snake_case__ ): _snake_case : Tuple = {} with zipfile.ZipFile(snake_case__ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case__ ): # read the file with z.open(snake_case__ ) as f: _snake_case : Any = f.read().decode("""UTF-8""" ) return results
64
1
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": A_ = argparse.ArgumentParser( description=( '''Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned''' ''' Distillation''' ) ) parser.add_argument('''--model_type''', default='''bert''', choices=['''bert''']) parser.add_argument('''--model_name''', default='''bert-base-uncased''', type=str) parser.add_argument('''--dump_checkpoint''', default='''serialization_dir/tf_bert-base-uncased_0247911.pth''', type=str) parser.add_argument('''--vocab_transform''', action='''store_true''') A_ = parser.parse_args() if args.model_type == "bert": A_ = BertForMaskedLM.from_pretrained(args.model_name) A_ = '''bert''' else: raise ValueError('''args.model_type should be "bert".''') A_ = model.state_dict() A_ = {} for w in ["word_embeddings", "position_embeddings"]: A_ = state_dict[F'''{prefix}.embeddings.{w}.weight'''] for w in ["weight", "bias"]: A_ = state_dict[F'''{prefix}.embeddings.LayerNorm.{w}'''] A_ = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}''' ] std_idx += 1 A_ = state_dict['''cls.predictions.decoder.weight'''] A_ = state_dict['''cls.predictions.bias'''] if args.vocab_transform: for w in ["weight", "bias"]: A_ = state_dict[F'''cls.predictions.transform.dense.{w}'''] A_ = state_dict[F'''cls.predictions.transform.LayerNorm.{w}'''] print(F'''N layers selected for distillation: {std_idx}''') print(F'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(F'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
64
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging A_ = logging.get_logger(__name__) class lowercase: '''simple docstring''' lowercase__ = 42 lowercase__ = None @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Tuple, a_: int, a_: int, a_: str, **a_: Dict ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any], a_: List[str] ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.is_available(): raise RuntimeError( f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}." ) @classmethod def UpperCamelCase_ ( cls: Tuple ): '''simple docstring''' return f"`pip install {cls.pip_package or cls.name}`" class lowercase( __a ): '''simple docstring''' lowercase__ = "optuna" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def UpperCamelCase_ ( self: Union[str, Any], a_: List[Any], a_: int, a_: str, **a_: List[str] ): '''simple docstring''' return run_hp_search_optuna(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], a_: Any ): '''simple docstring''' return default_hp_space_optuna(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "ray" lowercase__ = "'ray[tune]'" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_ray_available() def UpperCamelCase_ ( self: int, a_: Optional[Any], a_: int, a_: str, **a_: List[Any] ): '''simple docstring''' return run_hp_search_ray(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Tuple ): '''simple docstring''' return default_hp_space_ray(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "sigopt" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def UpperCamelCase_ ( self: Dict, a_: str, a_: int, a_: str, **a_: int ): '''simple docstring''' return run_hp_search_sigopt(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: List[str] ): '''simple docstring''' return default_hp_space_sigopt(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "wandb" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def UpperCamelCase_ ( self: Optional[Any], a_: str, a_: int, a_: str, **a_: Union[str, Any] ): '''simple docstring''' return run_hp_search_wandb(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Any ): '''simple docstring''' return default_hp_space_wandb(a_ ) A_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def UpperCAmelCase__ (): """simple docstring""" _snake_case : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(snake_case__ ) > 0: _snake_case : Any = available_backends[0].name if len(snake_case__ ) > 1: logger.info( F"{len(snake_case__ )} hyperparameter search backends available. Using {name} as the default." ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( F" - To install {backend.name} run {backend.pip_install()}" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
64
1
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : Optional[int] = torch.exp(snake_case__ ) _snake_case : List[str] = torch.sum(snake_case__ , dim=1 ) # sum of exp(x_i) _snake_case : List[str] = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(snake_case__ ) - B / A class lowercase( nn.Module ): '''simple docstring''' def __init__( self: str, a_: Dict ): '''simple docstring''' super().__init__() _snake_case : List[str] = config.output_attentions _snake_case : int = config.output_hidden_states _snake_case : Optional[Any] = nn.ModuleList([BertLayer(a_ ) for _ in range(config.num_hidden_layers )] ) _snake_case : Union[str, Any] = nn.ModuleList([BertHighway(a_ ) for _ in range(config.num_hidden_layers )] ) _snake_case : Dict = [-1 for _ in range(config.num_hidden_layers )] def UpperCamelCase_ ( self: str, a_: List[Any] ): '''simple docstring''' if (type(a_ ) is float) or (type(a_ ) is int): for i in range(len(self.early_exit_entropy ) ): _snake_case : Optional[Any] = x else: _snake_case : Dict = x def UpperCamelCase_ ( self: List[str], a_: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def UpperCamelCase_ ( self: Union[str, Any], a_: List[Any], a_: Union[str, Any]=None, a_: Any=None, a_: Union[str, Any]=None, a_: Optional[Any]=None, ): '''simple docstring''' _snake_case : int = () _snake_case : Union[str, Any] = () _snake_case : Any = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _snake_case : str = all_hidden_states + (hidden_states,) _snake_case : Any = layer_module( a_, a_, head_mask[i], a_, a_ ) _snake_case : Optional[int] = layer_outputs[0] if self.output_attentions: _snake_case : List[Any] = all_attentions + (layer_outputs[1],) _snake_case : Optional[int] = (hidden_states,) if self.output_hidden_states: _snake_case : Any = current_outputs + (all_hidden_states,) if self.output_attentions: _snake_case : int = current_outputs + (all_attentions,) _snake_case : Union[str, Any] = self.highway[i](a_ ) # logits, pooled_output if not self.training: _snake_case : Optional[int] = highway_exit[0] _snake_case : Tuple = entropy(a_ ) _snake_case : Union[str, Any] = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _snake_case : Any = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _snake_case : Optional[Any] = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(a_, i + 1 ) else: _snake_case : str = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _snake_case : str = all_hidden_states + (hidden_states,) _snake_case : Any = (hidden_states,) if self.output_hidden_states: _snake_case : Optional[Any] = outputs + (all_hidden_states,) if self.output_attentions: _snake_case : Tuple = outputs + (all_attentions,) _snake_case : int = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , __a , ) class lowercase( __a ): '''simple docstring''' def __init__( self: Dict, a_: int ): '''simple docstring''' super().__init__(a_ ) _snake_case : Dict = config _snake_case : List[str] = BertEmbeddings(a_ ) _snake_case : Dict = DeeBertEncoder(a_ ) _snake_case : int = BertPooler(a_ ) self.init_weights() def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' self.encoder.init_highway_pooler(self.pooler ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' return self.embeddings.word_embeddings def UpperCamelCase_ ( self: Optional[Any], a_: int ): '''simple docstring''' _snake_case : Union[str, Any] = value def UpperCamelCase_ ( self: Any, a_: int ): '''simple docstring''' for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(a_ ) @add_start_docstrings_to_model_forward(a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Union[str, Any]=None, a_: Tuple=None, a_: str=None, a_: List[str]=None, a_: Any=None, a_: Optional[Any]=None, a_: Optional[int]=None, a_: str=None, ): '''simple docstring''' if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: _snake_case : Optional[int] = input_ids.size() elif inputs_embeds is not None: _snake_case : int = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) _snake_case : str = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _snake_case : List[Any] = torch.ones(a_, device=a_ ) if encoder_attention_mask is None: _snake_case : Optional[int] = torch.ones(a_, device=a_ ) if token_type_ids is None: _snake_case : Optional[int] = torch.zeros(a_, dtype=torch.long, device=a_ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _snake_case : torch.Tensor = self.get_extended_attention_mask(a_, a_, a_ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _snake_case : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _snake_case : Optional[int] = encoder_attention_mask[:, None, None, :] _snake_case : List[str] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _snake_case : Union[str, Any] = (1.0 - encoder_extended_attention_mask) * -10_000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _snake_case : Optional[Any] = self.get_head_mask(a_, self.config.num_hidden_layers ) _snake_case : Optional[int] = self.embeddings( input_ids=a_, position_ids=a_, token_type_ids=a_, inputs_embeds=a_ ) _snake_case : Optional[int] = self.encoder( a_, attention_mask=a_, head_mask=a_, encoder_hidden_states=a_, encoder_attention_mask=a_, ) _snake_case : Union[str, Any] = encoder_outputs[0] _snake_case : Union[str, Any] = self.pooler(a_ ) _snake_case : Optional[Any] = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class lowercase( __a ): '''simple docstring''' def __init__( self: List[Any], a_: Optional[int], a_: Any ): '''simple docstring''' _snake_case : Tuple = message _snake_case : Tuple = exit_layer # start from 1! class lowercase( nn.Module ): '''simple docstring''' def __init__( self: List[str], a_: Tuple ): '''simple docstring''' super().__init__() _snake_case : List[str] = BertPooler(a_ ) _snake_case : Optional[int] = nn.Dropout(config.hidden_dropout_prob ) _snake_case : str = nn.Linear(config.hidden_size, config.num_labels ) def UpperCamelCase_ ( self: Optional[int], a_: List[str] ): '''simple docstring''' _snake_case : Dict = encoder_outputs[0] _snake_case : List[Any] = self.pooler(a_ ) # "return" pooler_output # BertModel _snake_case : Dict = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _snake_case : int = bmodel_output[1] _snake_case : int = self.dropout(a_ ) _snake_case : List[Any] = self.classifier(a_ ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , __a , ) class lowercase( __a ): '''simple docstring''' def __init__( self: str, a_: Dict ): '''simple docstring''' super().__init__(a_ ) _snake_case : Optional[Any] = config.num_labels _snake_case : List[str] = config.num_hidden_layers _snake_case : Union[str, Any] = DeeBertModel(a_ ) _snake_case : List[str] = nn.Dropout(config.hidden_dropout_prob ) _snake_case : Tuple = nn.Linear(config.hidden_size, self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(a_ ) def UpperCamelCase_ ( self: Optional[int], a_: List[str]=None, a_: int=None, a_: Any=None, a_: Tuple=None, a_: Tuple=None, a_: int=None, a_: List[Any]=None, a_: Optional[int]=-1, a_: Optional[int]=False, ): '''simple docstring''' _snake_case : Optional[int] = self.num_layers try: _snake_case : Dict = self.bert( a_, attention_mask=a_, token_type_ids=a_, position_ids=a_, head_mask=a_, inputs_embeds=a_, ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _snake_case : Dict = outputs[1] _snake_case : Any = self.dropout(a_ ) _snake_case : List[str] = self.classifier(a_ ) _snake_case : Optional[int] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _snake_case : List[str] = e.message _snake_case : Dict = e.exit_layer _snake_case : Union[str, Any] = outputs[0] if not self.training: _snake_case : Union[str, Any] = entropy(a_ ) _snake_case : str = [] _snake_case : Dict = [] if labels is not None: if self.num_labels == 1: # We are doing regression _snake_case : Any = MSELoss() _snake_case : List[str] = loss_fct(logits.view(-1 ), labels.view(-1 ) ) else: _snake_case : Dict = CrossEntropyLoss() _snake_case : int = loss_fct(logits.view(-1, self.num_labels ), labels.view(-1 ) ) # work with highway exits _snake_case : Optional[Any] = [] for highway_exit in outputs[-1]: _snake_case : List[Any] = highway_exit[0] if not self.training: highway_logits_all.append(a_ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _snake_case : Dict = MSELoss() _snake_case : Optional[Any] = loss_fct(highway_logits.view(-1 ), labels.view(-1 ) ) else: _snake_case : Optional[int] = CrossEntropyLoss() _snake_case : str = loss_fct(highway_logits.view(-1, self.num_labels ), labels.view(-1 ) ) highway_losses.append(a_ ) if train_highway: _snake_case : Optional[Any] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _snake_case : List[Any] = (loss,) + outputs if not self.training: _snake_case : List[str] = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _snake_case : List[str] = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
64
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowercase( __a ): '''simple docstring''' lowercase__ = ["image_processor", "tokenizer"] lowercase__ = "AutoImageProcessor" lowercase__ = "AutoTokenizer" def __init__( self: List[str], a_: List[str]=None, a_: Tuple=None, **a_: Tuple ): '''simple docstring''' _snake_case : str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""", a_, ) _snake_case : str = kwargs.pop("""feature_extractor""" ) _snake_case : Union[str, Any] = 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__(a_, a_ ) _snake_case : Dict = self.image_processor _snake_case : Any = False def __call__( self: Any, *a_: Any, **a_: Tuple ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*a_, **a_ ) _snake_case : Dict = kwargs.pop("""images""", a_ ) _snake_case : Optional[Any] = kwargs.pop("""text""", a_ ) if len(a_ ) > 0: _snake_case : Optional[int] = args[0] _snake_case : Tuple = args[1:] if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: _snake_case : Tuple = self.image_processor(a_, *a_, **a_ ) if text is not None: _snake_case : Tuple = self.tokenizer(a_, **a_ ) if text is None: return inputs elif images is None: return encodings else: _snake_case : List[str] = encodings["""input_ids"""] return inputs def UpperCamelCase_ ( self: Optional[int], *a_: Tuple, **a_: List[str] ): '''simple docstring''' return self.tokenizer.batch_decode(*a_, **a_ ) def UpperCamelCase_ ( self: int, *a_: List[str], **a_: int ): '''simple docstring''' return self.tokenizer.decode(*a_, **a_ ) @contextmanager def UpperCamelCase_ ( self: Dict ): '''simple docstring''' warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your images inputs, or in a separate call.""" ) _snake_case : Any = True _snake_case : Optional[int] = self.tokenizer yield _snake_case : int = self.image_processor _snake_case : Optional[int] = False def UpperCamelCase_ ( self: Dict, a_: Optional[Any], a_: str=False, a_: Optional[Any]=None ): '''simple docstring''' if added_vocab is None: _snake_case : Dict = self.tokenizer.get_added_vocab() _snake_case : str = {} while tokens: _snake_case : Union[str, Any] = re.search(r"""<s_(.*?)>""", a_, re.IGNORECASE ) if start_token is None: break _snake_case : List[Any] = start_token.group(1 ) _snake_case : str = re.search(rf"</s_{key}>", a_, re.IGNORECASE ) _snake_case : Dict = start_token.group() if end_token is None: _snake_case : List[Any] = tokens.replace(a_, """""" ) else: _snake_case : List[str] = end_token.group() _snake_case : str = re.escape(a_ ) _snake_case : str = re.escape(a_ ) _snake_case : Union[str, Any] = re.search(f"{start_token_escaped}(.*?){end_token_escaped}", a_, re.IGNORECASE ) if content is not None: _snake_case : int = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node _snake_case : List[Any] = self.tokenajson(a_, is_inner_value=a_, added_vocab=a_ ) if value: if len(a_ ) == 1: _snake_case : List[str] = value[0] _snake_case : List[str] = value else: # leaf nodes _snake_case : Tuple = [] for leaf in content.split(r"""<sep/>""" ): _snake_case : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": _snake_case : int = leaf[1:-2] # for categorical special tokens output[key].append(a_ ) if len(output[key] ) == 1: _snake_case : int = output[key][0] _snake_case : Any = tokens[tokens.find(a_ ) + len(a_ ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=a_, added_vocab=a_ ) if len(a_ ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""", a_, ) return self.image_processor_class @property def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""", a_, ) return self.image_processor
64
1
"""simple docstring""" import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup A_ = logging.get_logger(__name__) class lowercase( __a ): '''simple docstring''' def __init__( self: List[Any], **a_: List[Any] ): '''simple docstring''' requires_backends(self, ["""bs4"""] ) super().__init__(**a_ ) def UpperCamelCase_ ( self: List[Any], a_: Optional[Any] ): '''simple docstring''' _snake_case : Any = [] _snake_case : List[Any] = [] _snake_case : Dict = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag _snake_case : Any = parent.find_all(child.name, recursive=a_ ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(a_ ) else next(i for i, s in enumerate(a_, 1 ) if s is child ) ) _snake_case : Union[str, Any] = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def UpperCamelCase_ ( self: List[str], a_: Dict ): '''simple docstring''' _snake_case : Tuple = BeautifulSoup(a_, """html.parser""" ) _snake_case : Any = [] _snake_case : Dict = [] _snake_case : str = [] for element in html_code.descendants: if type(a_ ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue _snake_case : Dict = html.unescape(a_ ).strip() if not text_in_this_tag: continue all_doc_strings.append(a_ ) _snake_case , _snake_case : Dict = self.xpath_soup(a_ ) stringaxtag_seq.append(a_ ) stringaxsubs_seq.append(a_ ) if len(a_ ) != len(a_ ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(a_ ) != len(a_ ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def UpperCamelCase_ ( self: List[str], a_: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : str = """""" for tagname, subs in zip(a_, a_ ): xpath += f"/{tagname}" if subs != 0: xpath += f"[{subs}]" return xpath def __call__( self: Tuple, a_: List[str] ): '''simple docstring''' _snake_case : List[Any] = False # Check that strings has a valid type if isinstance(a_, a_ ): _snake_case : Optional[int] = True elif isinstance(a_, (list, tuple) ): if len(a_ ) == 0 or isinstance(html_strings[0], a_ ): _snake_case : int = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ f"but is of type {type(a_ )}." ) _snake_case : int = bool(isinstance(a_, (list, tuple) ) and (isinstance(html_strings[0], a_ )) ) if not is_batched: _snake_case : List[Any] = [html_strings] # Get nodes + xpaths _snake_case : List[str] = [] _snake_case : Any = [] for html_string in html_strings: _snake_case , _snake_case , _snake_case : Tuple = self.get_three_from_single(a_ ) nodes.append(a_ ) _snake_case : str = [] for node, tag_list, sub_list in zip(a_, a_, a_ ): _snake_case : Any = self.construct_xpath(a_, a_ ) xpath_strings.append(a_ ) xpaths.append(a_ ) # return as Dict _snake_case : int = {"""nodes""": nodes, """xpaths""": xpaths} _snake_case : Tuple = BatchFeature(data=a_, tensor_type=a_ ) return encoded_inputs
64
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : int = 0.00 _snake_case : int = 0 for resistor in resistors: if resistor <= 0: _snake_case : Dict = F"Resistor at index {index} has a negative or zero value!" raise ValueError(snake_case__ ) first_sum += 1 / float(snake_case__ ) index += 1 return 1 / first_sum def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : Union[str, Any] = 0.00 _snake_case : Any = 0 for resistor in resistors: sum_r += resistor if resistor < 0: _snake_case : Any = F"Resistor at index {index} has a negative value!" raise ValueError(snake_case__ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
64
1
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = DiTPipeline lowercase__ = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS lowercase__ = PipelineTesterMixin.required_optional_params - { "latents", "num_images_per_prompt", "callback", "callback_steps", } lowercase__ = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS lowercase__ = False def UpperCamelCase_ ( self: Any ): '''simple docstring''' torch.manual_seed(0 ) _snake_case : Tuple = TransformeraDModel( sample_size=16, num_layers=2, patch_size=4, attention_head_dim=8, num_attention_heads=2, in_channels=4, out_channels=8, attention_bias=a_, activation_fn="""gelu-approximate""", num_embeds_ada_norm=1_000, norm_type="""ada_norm_zero""", norm_elementwise_affine=a_, ) _snake_case : List[Any] = AutoencoderKL() _snake_case : Any = DDIMScheduler() _snake_case : Optional[Any] = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler} return components def UpperCamelCase_ ( self: Any, a_: Dict, a_: List[Any]=0 ): '''simple docstring''' if str(a_ ).startswith("""mps""" ): _snake_case : str = torch.manual_seed(a_ ) else: _snake_case : Dict = torch.Generator(device=a_ ).manual_seed(a_ ) _snake_case : Union[str, Any] = { """class_labels""": [1], """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Tuple = """cpu""" _snake_case : str = self.get_dummy_components() _snake_case : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : int = self.get_dummy_inputs(a_ ) _snake_case : Any = pipe(**a_ ).images _snake_case : Tuple = image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 16, 16, 3) ) _snake_case : List[str] = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457] ) _snake_case : Optional[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_, 1E-3 ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' self._test_inference_batch_single_identical(relax_max_difference=a_, expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available(), reason="""XFormers attention is only available with CUDA and `xformers` installed""", ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class lowercase( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : List[Any] = torch.manual_seed(0 ) _snake_case : Dict = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""" ) pipe.to("""cuda""" ) _snake_case : Optional[Any] = ["""vase""", """umbrella""", """white shark""", """white wolf"""] _snake_case : List[str] = pipe.get_label_ids(a_ ) _snake_case : List[str] = pipe(a_, generator=a_, num_inference_steps=40, output_type="""np""" ).images for word, image in zip(a_, a_ ): _snake_case : Dict = load_numpy( f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" ) assert np.abs((expected_image - image).max() ) < 1E-2 def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Dict = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""" ) _snake_case : List[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("""cuda""" ) _snake_case : Dict = ["""vase""", """umbrella"""] _snake_case : List[str] = pipe.get_label_ids(a_ ) _snake_case : Tuple = torch.manual_seed(0 ) _snake_case : Dict = pipe(a_, generator=a_, num_inference_steps=25, output_type="""np""" ).images for word, image in zip(a_, a_ ): _snake_case : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" f"/dit/{word}_512.npy" ) assert np.abs((expected_image - image).max() ) < 1E-1
64
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''', }, '''merges_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''Salesforce/codegen-350M-mono''': ( '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json''' ), }, } A_ = { '''Salesforce/codegen-350M-mono''': 20_48, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] lowercase__ = CodeGenTokenizer def __init__( self: Union[str, Any], a_: List[Any]=None, a_: str=None, a_: str=None, a_: Dict="<|endoftext|>", a_: Tuple="<|endoftext|>", a_: str="<|endoftext|>", a_: List[Any]=False, **a_: List[str], ): '''simple docstring''' super().__init__( a_, a_, tokenizer_file=a_, unk_token=a_, bos_token=a_, eos_token=a_, add_prefix_space=a_, **a_, ) if kwargs.pop("""add_bos_token""", a_ ): _snake_case : str = kwargs.pop("""name_or_path""", """""" ) raise ValueError( """Currenty GPT2's fast tokenizer does NOT support adding a BOS token.""" """Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n""" f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n" f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n" """This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.""" """ so that the fast tokenizer works correctly.""" ) _snake_case : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : Dict = getattr(a_, pre_tok_state.pop("""type""" ) ) _snake_case : Dict = add_prefix_space _snake_case : str = pre_tok_class(**a_ ) _snake_case : List[Any] = add_prefix_space def UpperCamelCase_ ( self: Any, *a_: Any, **a_: int ): '''simple docstring''' _snake_case : Optional[int] = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], *a_: Any, **a_: List[str] ): '''simple docstring''' _snake_case : Dict = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : List[Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ ) def UpperCamelCase_ ( self: str, a_: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], a_: bool = False, a_: bool = None, a_: Optional[List[str]] = None, **a_: List[str], ): '''simple docstring''' _snake_case : Any = super().decode( token_ids=a_, skip_special_tokens=a_, clean_up_tokenization_spaces=a_, **a_, ) if truncate_before_pattern is not None and len(a_ ) > 0: _snake_case : List[str] = self.truncate(a_, a_ ) return decoded_text def UpperCamelCase_ ( self: Dict, a_: Tuple, a_: Optional[Any] ): '''simple docstring''' def find_re(a_: Dict, a_: str, a_: Union[str, Any] ): _snake_case : Any = pattern.search(a_, a_ ) return m.start() if m else -1 _snake_case : Tuple = [re.compile(a_, re.MULTILINE ) for pattern in truncate_before_pattern] _snake_case : List[Any] = list(re.finditer("""^print""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : int = completion[: prints[1].start()] _snake_case : List[str] = list(re.finditer("""^def""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : List[Any] = completion[: defs[1].start()] _snake_case : int = 0 _snake_case : List[Any] = [ pos for pos in [find_re(a_, a_, a_ ) for terminal in terminals] if pos != -1 ] if len(a_ ) > 0: return completion[: min(a_ )] else: return completion
64
1
"""simple docstring""" from math import log from scipy.constants import Boltzmann, physical_constants A_ = 3_00 # TEMPERATURE (unit = K) def UpperCAmelCase__ (snake_case__ : float , snake_case__ : float , snake_case__ : float , ): """simple docstring""" if donor_conc <= 0: raise ValueError("""Donor concentration should be positive""" ) elif acceptor_conc <= 0: raise ValueError("""Acceptor concentration should be positive""" ) elif intrinsic_conc <= 0: raise ValueError("""Intrinsic concentration should be positive""" ) elif donor_conc <= intrinsic_conc: raise ValueError( """Donor concentration should be greater than intrinsic concentration""" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( """Acceptor concentration should be greater than intrinsic concentration""" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
64
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : List[Any] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _snake_case : Tuple = 1_92 _snake_case : Any = 7_68 _snake_case : Any = 12 _snake_case : List[Any] = 3 _snake_case : int = [8_00, 13_33] _snake_case : Tuple = False elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = 3_30 _snake_case : List[str] = 14 _snake_case : List[str] = 6 _snake_case : Union[str, Any] = 13_20 elif "yolos_s" in yolos_name: _snake_case : Union[str, Any] = 3_84 _snake_case : List[str] = 15_36 _snake_case : Any = 12 _snake_case : Optional[int] = 6 elif "yolos_b" in yolos_name: _snake_case : Dict = [8_00, 13_44] _snake_case : str = 91 _snake_case : Optional[Any] = """huggingface/label-files""" _snake_case : str = """coco-detection-id2label.json""" _snake_case : str = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="""dataset""" ) , """r""" ) ) _snake_case : Union[str, Any] = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[str] = idalabel _snake_case : List[str] = {v: k for k, v in idalabel.items()} return config def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosConfig , snake_case__ : bool = False ): """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : int = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) _snake_case : Union[str, Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Any = in_proj_weight[: config.hidden_size, :] _snake_case : Optional[Any] = in_proj_bias[: config.hidden_size] _snake_case : Optional[int] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Tuple = in_proj_weight[-config.hidden_size :, :] _snake_case : List[Any] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" if "backbone" in name: _snake_case : str = name.replace("""backbone""" , """vit""" ) if "cls_token" in name: _snake_case : Union[str, Any] = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "det_token" in name: _snake_case : str = name.replace("""det_token""" , """embeddings.detection_tokens""" ) if "mid_pos_embed" in name: _snake_case : str = name.replace("""mid_pos_embed""" , """encoder.mid_position_embeddings""" ) if "pos_embed" in name: _snake_case : Tuple = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: _snake_case : str = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "blocks" in name: _snake_case : str = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: _snake_case : Any = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: _snake_case : str = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: _snake_case : List[str] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: _snake_case : str = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: _snake_case : List[str] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: _snake_case : int = name.replace("""mlp.fc2""" , """output.dense""" ) if "class_embed" in name: _snake_case : Union[str, Any] = name.replace("""class_embed""" , """class_labels_classifier""" ) if "bbox_embed" in name: _snake_case : str = name.replace("""bbox_embed""" , """bbox_predictor""" ) if "vit.norm" in name: _snake_case : Union[str, Any] = name.replace("""vit.norm""" , """vit.layernorm""" ) return name def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosForObjectDetection ): """simple docstring""" for key in orig_state_dict.copy().keys(): _snake_case : List[str] = orig_state_dict.pop(snake_case__ ) if "qkv" in key: _snake_case : Optional[Any] = key.split(""".""" ) _snake_case : Optional[Any] = int(key_split[2] ) _snake_case : Optional[int] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _snake_case : str = val[:dim, :] _snake_case : Optional[Any] = val[ dim : dim * 2, : ] _snake_case : Optional[Any] = val[-dim:, :] else: _snake_case : Dict = val[:dim] _snake_case : Any = val[dim : dim * 2] _snake_case : Dict = val[-dim:] else: _snake_case : Tuple = val return orig_state_dict def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Union[str, Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : str , snake_case__ : bool = False ): """simple docstring""" _snake_case : Optional[Any] = get_yolos_config(snake_case__ ) # load original state_dict _snake_case : Optional[int] = torch.load(snake_case__ , map_location="""cpu""" )["""model"""] # load 🤗 model _snake_case : Optional[Any] = YolosForObjectDetection(snake_case__ ) model.eval() _snake_case : Optional[Any] = convert_state_dict(snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ ) # Check outputs on an image, prepared by YolosImageProcessor _snake_case : List[str] = 8_00 if yolos_name != """yolos_ti""" else 5_12 _snake_case : Optional[int] = YolosImageProcessor(format="""coco_detection""" , size=snake_case__ ) _snake_case : Optional[Any] = image_processor(images=prepare_img() , return_tensors="""pt""" ) _snake_case : Optional[Any] = model(**snake_case__ ) _snake_case , _snake_case : Optional[int] = outputs.logits, outputs.pred_boxes _snake_case , _snake_case : Dict = None, None if yolos_name == "yolos_ti": _snake_case : Optional[Any] = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) _snake_case : Tuple = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": _snake_case : List[str] = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) _snake_case : List[str] = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": _snake_case : Dict = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) _snake_case : Union[str, Any] = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) _snake_case : Optional[Any] = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": _snake_case : int = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) _snake_case : Optional[int] = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(F"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , snake_case__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , snake_case__ , atol=1e-4 ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if push_to_hub: _snake_case : Dict = { """yolos_ti""": """yolos-tiny""", """yolos_s_200_pre""": """yolos-small""", """yolos_s_300_pre""": """yolos-small-300""", """yolos_s_dWr""": """yolos-small-dwr""", """yolos_base""": """yolos-base""", } print("""Pushing to the hub...""" ) _snake_case : str = model_mapping[yolos_name] image_processor.push_to_hub(snake_case__ , organization="""hustvl""" ) model.push_to_hub(snake_case__ , organization="""hustvl""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.pth file).''' ) 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.''' ) A_ = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
64
1
"""simple docstring""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class lowercase: '''simple docstring''' def __init__( self: str, a_: List[Any], a_: Optional[Any]=99, a_: Tuple=13, a_: Tuple=16, a_: Union[str, Any]=7, a_: Union[str, Any]=True, a_: Dict=True, a_: Optional[Any]=True, a_: Tuple=False, a_: Any=True, a_: List[Any]=2, a_: Tuple=32, a_: int=4, a_: Tuple=4, a_: Dict=30, a_: Dict=0, a_: str=1, a_: Any=2, a_: Union[str, Any]=None, ): '''simple docstring''' _snake_case : Dict = parent _snake_case : Tuple = batch_size _snake_case : Optional[Any] = decoder_seq_length # For common tests _snake_case : int = self.decoder_seq_length _snake_case : Union[str, Any] = is_training _snake_case : Optional[Any] = use_attention_mask _snake_case : Tuple = use_labels _snake_case : List[Any] = vocab_size _snake_case : Optional[int] = d_model _snake_case : Dict = d_model _snake_case : str = decoder_layers _snake_case : Tuple = decoder_layers _snake_case : Optional[int] = decoder_ffn_dim _snake_case : Any = decoder_attention_heads _snake_case : List[Any] = decoder_attention_heads _snake_case : Optional[int] = eos_token_id _snake_case : Optional[Any] = bos_token_id _snake_case : Tuple = pad_token_id _snake_case : int = decoder_start_token_id _snake_case : Optional[int] = use_cache _snake_case : Dict = max_position_embeddings _snake_case : Union[str, Any] = None _snake_case : Dict = decoder_seq_length _snake_case : Tuple = 2 _snake_case : Union[str, Any] = 1 def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : str = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size ) _snake_case : Any = None if self.use_attention_mask: _snake_case : Tuple = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2 ) _snake_case : Union[str, Any] = None if self.use_labels: _snake_case : Dict = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size ) _snake_case : Union[str, Any] = TrOCRConfig( vocab_size=self.vocab_size, d_model=self.d_model, decoder_layers=self.decoder_layers, decoder_ffn_dim=self.decoder_ffn_dim, decoder_attention_heads=self.decoder_attention_heads, eos_token_id=self.eos_token_id, bos_token_id=self.bos_token_id, use_cache=self.use_cache, pad_token_id=self.pad_token_id, decoder_start_token_id=self.decoder_start_token_id, max_position_embeddings=self.max_position_embeddings, ) return (config, input_ids, attention_mask, lm_labels) def UpperCamelCase_ ( self: List[str], a_: List[Any], a_: Optional[int], a_: Optional[int], a_: Optional[Any], ): '''simple docstring''' _snake_case : int = True _snake_case : List[Any] = TrOCRDecoder(config=a_ ).to(a_ ).eval() _snake_case : Tuple = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass _snake_case : Tuple = model(a_, use_cache=a_ ) _snake_case : Optional[int] = model(a_ ) _snake_case : str = model(a_, use_cache=a_ ) self.parent.assertTrue(len(a_ ) == len(a_ ) ) self.parent.assertTrue(len(a_ ) == len(a_ ) + 1 ) _snake_case : List[Any] = outputs["""past_key_values"""] # create hypothetical next token and extent to next_input_ids _snake_case : Tuple = ids_tensor((2, 1), config.vocab_size - 1 ) + 1 # append to next input_ids and _snake_case : Optional[int] = torch.cat([input_ids, next_tokens], dim=-1 ) _snake_case : List[str] = model(a_ )["""last_hidden_state"""] _snake_case : Optional[Any] = model(a_, past_key_values=a_ )["""last_hidden_state"""] # select random slice _snake_case : List[str] = ids_tensor((1,), output_from_past.shape[-1] ).item() _snake_case : Optional[int] = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() _snake_case : Union[str, Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(a_, a_, atol=1E-3 ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Optional[Any] = self.prepare_config_and_inputs() _snake_case , _snake_case , _snake_case , _snake_case : str = config_and_inputs _snake_case : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_torch class lowercase( __a , __a , __a , unittest.TestCase ): '''simple docstring''' lowercase__ = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowercase__ = (TrOCRForCausalLM,) if is_torch_available() else () lowercase__ = {"text-generation": TrOCRForCausalLM} if is_torch_available() else {} lowercase__ = True lowercase__ = False def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Tuple = TrOCRStandaloneDecoderModelTester(self, is_training=a_ ) _snake_case : str = ConfigTester(self, config_class=a_ ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self: int ): '''simple docstring''' pass def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' pass def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*a_ ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' return @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' pass
64
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str]=False ): """simple docstring""" _snake_case : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"module.blocks.{i}.norm1.weight", F"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((F"module.blocks.{i}.norm1.bias", F"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (F"module.blocks.{i}.attn.proj.weight", F"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.attn.proj.bias", F"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((F"module.blocks.{i}.norm2.weight", F"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((F"module.blocks.{i}.norm2.bias", F"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.weight", F"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.bias", F"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.weight", F"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.bias", F"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _snake_case : Any = [(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 UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : Dict , snake_case__ : List[str]=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _snake_case : List[Any] = """""" else: _snake_case : List[Any] = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.weight" ) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Optional[Any] = in_proj_weight[ : config.hidden_size, : ] _snake_case : Union[str, Any] = in_proj_bias[: config.hidden_size] _snake_case : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] _snake_case : List[str] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Tuple = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" _snake_case : List[str] = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : int ): """simple docstring""" _snake_case : Optional[Any] = dct.pop(snake_case__ ) _snake_case : Union[str, Any] = val def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : str ): """simple docstring""" _snake_case : str = ViTMSNConfig() _snake_case : Any = 10_00 _snake_case : Tuple = """datasets/huggingface/label-files""" _snake_case : Dict = """imagenet-1k-id2label.json""" _snake_case : int = json.load(open(hf_hub_download(snake_case__ , snake_case__ ) , """r""" ) ) _snake_case : Any = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[Any] = idalabel _snake_case : str = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: _snake_case : Tuple = 3_84 _snake_case : Dict = 15_36 _snake_case : Tuple = 6 elif "l16" in checkpoint_url: _snake_case : Any = 10_24 _snake_case : int = 40_96 _snake_case : str = 24 _snake_case : Optional[int] = 16 _snake_case : List[Any] = 0.1 elif "b4" in checkpoint_url: _snake_case : Tuple = 4 elif "l7" in checkpoint_url: _snake_case : int = 7 _snake_case : Dict = 10_24 _snake_case : Optional[Any] = 40_96 _snake_case : Any = 24 _snake_case : Union[str, Any] = 16 _snake_case : Optional[int] = 0.1 _snake_case : int = ViTMSNModel(snake_case__ ) _snake_case : Optional[int] = torch.hub.load_state_dict_from_url(snake_case__ , map_location="""cpu""" )["""target_encoder"""] _snake_case : List[str] = ViTImageProcessor(size=config.image_size ) remove_projection_head(snake_case__ ) _snake_case : List[str] = create_rename_keys(snake_case__ , base_model=snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_q_k_v(snake_case__ , snake_case__ , base_model=snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() _snake_case : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) _snake_case : str = ViTImageProcessor( size=config.image_size , image_mean=snake_case__ , image_std=snake_case__ ) _snake_case : Any = image_processor(images=snake_case__ , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) _snake_case : int = model(**snake_case__ ) _snake_case : List[Any] = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: _snake_case : Optional[Any] = torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] ) elif "b16" in checkpoint_url: _snake_case : str = torch.tensor([[14.28_89, -18.90_45, 11.72_81]] ) elif "l16" in checkpoint_url: _snake_case : Optional[int] = torch.tensor([[41.50_28, -22.86_81, 45.64_75]] ) elif "b4" in checkpoint_url: _snake_case : List[Any] = torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] ) else: _snake_case : Optional[int] = torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , snake_case__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A_ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
64
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType A_ = logging.get_logger(__name__) A_ = { '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class lowercase( __a ): '''simple docstring''' lowercase__ = "deberta-v2" def __init__( self: List[str], a_: Tuple=128_100, a_: Union[str, Any]=1_536, a_: Optional[Any]=24, a_: Union[str, Any]=24, a_: Dict=6_144, a_: Optional[int]="gelu", a_: Dict=0.1, a_: Dict=0.1, a_: Optional[int]=512, a_: Dict=0, a_: List[str]=0.02, a_: Optional[int]=1E-7, a_: Dict=False, a_: Optional[int]=-1, a_: Optional[int]=0, a_: str=True, a_: Dict=None, a_: Union[str, Any]=0, a_: str="gelu", **a_: List[str], ): '''simple docstring''' super().__init__(**a_ ) _snake_case : Union[str, Any] = hidden_size _snake_case : Tuple = num_hidden_layers _snake_case : Any = num_attention_heads _snake_case : Any = intermediate_size _snake_case : Optional[int] = hidden_act _snake_case : List[Any] = hidden_dropout_prob _snake_case : int = attention_probs_dropout_prob _snake_case : Optional[int] = max_position_embeddings _snake_case : List[Any] = type_vocab_size _snake_case : Optional[Any] = initializer_range _snake_case : List[Any] = relative_attention _snake_case : Any = max_relative_positions _snake_case : Union[str, Any] = pad_token_id _snake_case : Any = position_biased_input # Backwards compatibility if type(a_ ) == str: _snake_case : Optional[int] = [x.strip() for x in pos_att_type.lower().split("""|""" )] _snake_case : Optional[int] = pos_att_type _snake_case : str = vocab_size _snake_case : Optional[Any] = layer_norm_eps _snake_case : Optional[Any] = kwargs.get("""pooler_hidden_size""", a_ ) _snake_case : Tuple = pooler_dropout _snake_case : List[str] = pooler_hidden_act class lowercase( __a ): '''simple docstring''' @property def UpperCamelCase_ ( self: str ): '''simple docstring''' if self.task == "multiple-choice": _snake_case : Any = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _snake_case : Dict = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' return 12 def UpperCamelCase_ ( self: str, a_: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"], a_: int = -1, a_: int = -1, a_: int = -1, a_: bool = False, a_: Optional["TensorType"] = None, a_: int = 3, a_: int = 40, a_: int = 40, a_: "PreTrainedTokenizerBase" = None, ): '''simple docstring''' _snake_case : Optional[int] = super().generate_dummy_inputs(preprocessor=a_, framework=a_ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
64
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str ): """simple docstring""" _snake_case : Optional[Any] = list(snake_case__ ) _snake_case : List[Any] = list(snake_case__ ) _snake_case : List[Any] = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count += 1 _snake_case : Any = """_""" if count > 1: return False else: return "".join(snake_case__ ) def UpperCAmelCase__ (snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [] while True: _snake_case : Union[str, Any] = ["""$"""] * len(snake_case__ ) _snake_case : int = [] for i in range(len(snake_case__ ) ): for j in range(i + 1 , len(snake_case__ ) ): _snake_case : List[Any] = compare_string(binary[i] , binary[j] ) if k is False: _snake_case : Dict = """*""" _snake_case : List[Any] = """*""" temp.append("""X""" ) for i in range(len(snake_case__ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case__ ) == 0: return pi _snake_case : Optional[int] = list(set(snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Sequence[float] ): """simple docstring""" _snake_case : Optional[int] = [] for minterm in minterms: _snake_case : Any = """""" for _ in range(snake_case__ ): _snake_case : Optional[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case__ ) return temp def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : int ): """simple docstring""" _snake_case : Dict = list(snake_case__ ) _snake_case : List[str] = list(snake_case__ ) _snake_case : Tuple = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCAmelCase__ (snake_case__ : list[list[int]] , snake_case__ : list[str] ): """simple docstring""" _snake_case : Any = [] _snake_case : Union[str, Any] = [0] * len(snake_case__ ) for i in range(len(chart[0] ) ): _snake_case : Tuple = 0 _snake_case : str = -1 for j in range(len(snake_case__ ) ): if chart[j][i] == 1: count += 1 _snake_case : Union[str, Any] = j if count == 1: _snake_case : Union[str, Any] = 1 for i in range(len(snake_case__ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case__ ) ): _snake_case : List[Any] = 0 temp.append(prime_implicants[i] ) while True: _snake_case : Optional[int] = 0 _snake_case : str = -1 _snake_case : Any = 0 for i in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _snake_case : Dict = count_n _snake_case : Dict = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case__ ) ): _snake_case : Optional[Any] = 0 def UpperCAmelCase__ (snake_case__ : list[str] , snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [[0 for x in range(len(snake_case__ ) )] for x in range(len(snake_case__ ) )] for i in range(len(snake_case__ ) ): _snake_case : Any = prime_implicants[i].count("""_""" ) for j in range(len(snake_case__ ) ): if is_for_table(prime_implicants[i] , binary[j] , snake_case__ ): _snake_case : Tuple = 1 return chart def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = int(input("""Enter the no. of variables\n""" ) ) _snake_case : List[str] = [ float(snake_case__ ) for x in input( """Enter the decimal representation of Minterms 'Spaces Separated'\n""" ).split() ] _snake_case : List[str] = decimal_to_binary(snake_case__ , snake_case__ ) _snake_case : str = check(snake_case__ ) print("""Prime Implicants are:""" ) print(snake_case__ ) _snake_case : int = prime_implicant_chart(snake_case__ , snake_case__ ) _snake_case : str = selection(snake_case__ , snake_case__ ) print("""Essential Prime Implicants are:""" ) print(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
64
1
"""simple docstring""" from graphs.minimum_spanning_tree_kruskal import kruskal def UpperCAmelCase__ (): """simple docstring""" _snake_case : Union[str, Any] = 9 _snake_case : Dict = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] _snake_case : Optional[int] = kruskal(snake_case__ , snake_case__ ) _snake_case : List[Any] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(snake_case__ ) == sorted(snake_case__ )
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" stooge(snake_case__ , 0 , len(snake_case__ ) - 1 ) return arr def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int ): """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _snake_case , _snake_case : Tuple = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _snake_case : Dict = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case__ , i + t , (snake_case__) ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(stooge_sort(unsorted))
64
1
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class lowercase( __a ): '''simple docstring''' @staticmethod @abstractmethod def UpperCamelCase_ ( a_: ArgumentParser ): '''simple docstring''' raise NotImplementedError() @abstractmethod def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' raise NotImplementedError()
64
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase( metaclass=__a ): '''simple docstring''' lowercase__ = ["note_seq"] def __init__( self: Dict, *a_: Union[str, Any], **a_: List[str] ): '''simple docstring''' requires_backends(self, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Optional[int], *a_: Any, **a_: Optional[Any] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Tuple, *a_: Optional[Any], **a_: List[str] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] )
64
1
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : Tuple = filter(lambda snake_case__ : p.requires_grad , model.parameters() ) _snake_case : str = sum([np.prod(p.size() ) for p in model_parameters] ) return params A_ = logging.getLogger(__name__) def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : Dict ): """simple docstring""" if metric == "rouge2": _snake_case : Any = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": _snake_case : Tuple = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": _snake_case : str = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( F"seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this" """ function.""" ) _snake_case : str = ModelCheckpoint( dirpath=snake_case__ , filename=snake_case__ , monitor=F"val_{metric}" , mode="""max""" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : Union[str, Any] ): """simple docstring""" return EarlyStopping( monitor=F"val_{metric}" , mode="""min""" if """loss""" in metric else """max""" , patience=snake_case__ , verbose=snake_case__ , ) class lowercase( pl.Callback ): '''simple docstring''' def UpperCamelCase_ ( self: Optional[int], a_: Optional[int], a_: int ): '''simple docstring''' _snake_case : Union[str, Any] = {f"lr_group_{i}": param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(a_ ) @rank_zero_only def UpperCamelCase_ ( self: int, a_: pl.Trainer, a_: pl.LightningModule, a_: str, a_: Tuple=True ): '''simple docstring''' logger.info(f"***** {type_path} results at step {trainer.global_step:05d} *****" ) _snake_case : int = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results _snake_case : int = Path(pl_module.hparams.output_dir ) if type_path == "test": _snake_case : Tuple = od / """test_results.txt""" _snake_case : str = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _snake_case : Optional[int] = od / f"{type_path}_results/{trainer.global_step:05d}.txt" _snake_case : Optional[Any] = od / f"{type_path}_generations/{trainer.global_step:05d}.txt" results_file.parent.mkdir(exist_ok=a_ ) generations_file.parent.mkdir(exist_ok=a_ ) with open(a_, """a+""" ) as writer: for key in sorted(a_ ): if key in ["log", "progress_bar", "preds"]: continue _snake_case : str = metrics[key] if isinstance(a_, torch.Tensor ): _snake_case : int = val.item() _snake_case : int = f"{key}: {val:.6f}\n" writer.write(a_ ) if not save_generations: return if "preds" in metrics: _snake_case : str = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(a_ ) @rank_zero_only def UpperCamelCase_ ( self: Tuple, a_: Optional[Any], a_: Any ): '''simple docstring''' try: _snake_case : Dict = pl_module.model.model.num_parameters() except AttributeError: _snake_case : Tuple = pl_module.model.num_parameters() _snake_case : int = count_trainable_parameters(a_ ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1E6, """grad_mp""": n_trainable_pars / 1E6} ) @rank_zero_only def UpperCamelCase_ ( self: List[str], a_: pl.Trainer, a_: pl.LightningModule ): '''simple docstring''' save_json(pl_module.metrics, pl_module.metrics_save_path ) return self._write_logs(a_, a_, """test""" ) @rank_zero_only def UpperCamelCase_ ( self: Tuple, a_: pl.Trainer, a_: Any ): '''simple docstring''' save_json(pl_module.metrics, pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
64
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : int = data _snake_case : Dict = [0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def UpperCamelCase_ ( a_: Optional[Any], a_: Dict ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xffffffff def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) _snake_case : Optional[int] = self.data + padding + struct.pack(""">Q""", 8 * len(self.data ) ) return padded_data def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def UpperCamelCase_ ( self: Optional[Any], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = list(struct.unpack(""">16L""", a_ ) ) + [0] * 64 for i in range(16, 80 ): _snake_case : List[Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = self.padding() _snake_case : str = self.split_blocks() for block in self.blocks: _snake_case : Any = self.expand_block(a_ ) _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = self.h for i in range(0, 80 ): if 0 <= i < 20: _snake_case : int = (b & c) | ((~b) & d) _snake_case : str = 0X5a827999 elif 20 <= i < 40: _snake_case : Optional[int] = b ^ c ^ d _snake_case : str = 0X6ed9eba1 elif 40 <= i < 60: _snake_case : List[Any] = (b & c) | (b & d) | (c & d) _snake_case : List[Any] = 0X8f1bbcdc elif 60 <= i < 80: _snake_case : List[Any] = b ^ c ^ d _snake_case : int = 0Xca62c1d6 _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = ( self.rotate(a_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(a_, 30 ), c, d, ) _snake_case : Union[str, Any] = ( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = B"""Test String""" assert SHAaHash(snake_case__ ).final_hash() == hashlib.shaa(snake_case__ ).hexdigest() # noqa: S324 def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _snake_case : Union[str, Any] = parser.parse_args() _snake_case : List[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _snake_case : str = f.read() else: _snake_case : int = bytes(snake_case__ , """utf-8""" ) print(SHAaHash(snake_case__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
64
1
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin A_ = get_tests_dir('''fixtures/test_sentencepiece.model''') A_ = get_tests_dir('''fixtures/test_sentencepiece_bpe.model''') A_ = '''pt''' if is_torch_available() else '''tf''' @require_sentencepiece @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CamembertTokenizer lowercase__ = CamembertTokenizerFast lowercase__ = True lowercase__ = True def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _snake_case : List[str] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : str = """<pad>""" _snake_case : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ), a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ), a_ ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1], """<pad>""" ) self.assertEqual(vocab_keys[-1], """<mask>""" ) self.assertEqual(len(a_ ), 1_004 ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 1_005 ) def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : List[Any] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) _snake_case : Dict = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _snake_case : Dict = """I was born in 92000, and this is falsé.""" _snake_case : List[str] = tokenizer.encode(a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) _snake_case : int = tokenizer.encode(a_, add_special_tokens=a_ ) _snake_case : int = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _snake_case : Any = tokenizer.convert_ids_to_tokens(a_ ) _snake_case : Optional[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : Tuple = self.get_tokenizer() _snake_case : Tuple = self.get_rust_tokenizer() _snake_case : List[Any] = """I was born in 92000, and this is falsé.""" _snake_case : int = tokenizer.tokenize(a_ ) _snake_case : Union[str, Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) _snake_case : Tuple = tokenizer.encode(a_, add_special_tokens=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) _snake_case : Any = self.get_rust_tokenizer() _snake_case : List[str] = tokenizer.encode(a_ ) _snake_case : str = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) @slow def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Optional[Any] = {"""input_ids""": [[5, 54, 7_196, 297, 30, 23, 776, 18, 11, 3_215, 3_705, 8_252, 22, 3_164, 1_181, 2_116, 29, 16, 813, 25, 791, 3_314, 20, 3_446, 38, 27_575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9_088, 20, 1_517, 8, 22_804, 18_818, 10, 38, 629, 607, 607, 142, 19, 7_196, 867, 56, 10_326, 24, 2_267, 20, 416, 5_072, 15_612, 233, 734, 7, 2_399, 27, 16, 3_015, 1_649, 7, 24, 20, 4_338, 2_399, 27, 13, 3_400, 14, 13, 6_189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _snake_case : List[str] = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=a_, model_name="""camembert-base""", revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""", sequences=a_, )
64
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings A_ = r''' [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: title_sep (`str`, *optional*, defaults to `" / "`): Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`]. doc_sep (`str`, *optional*, defaults to `" // "`): Separator inserted between the text of the retrieved document and the original input when calling [`RagRetriever`]. n_docs (`int`, *optional*, defaults to 5): Number of documents to retrieve. max_combined_length (`int`, *optional*, defaults to 300): Max length of contextualized input returned by [`~RagRetriever.__call__`]. retrieval_vector_size (`int`, *optional*, defaults to 768): Dimensionality of the document embeddings indexed by [`RagRetriever`]. retrieval_batch_size (`int`, *optional*, defaults to 8): Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated [`RagRetriever`]. dataset (`str`, *optional*, defaults to `"wiki_dpr"`): A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids using `datasets.list_datasets()`). dataset_split (`str`, *optional*, defaults to `"train"`) Which split of the `dataset` to load. index_name (`str`, *optional*, defaults to `"compressed"`) The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and `"compressed"`. index_path (`str`, *optional*) The path to the serialized faiss index on disk. passages_path (`str`, *optional*): A path to text passages compatible with the faiss index. Required if using [`~models.rag.retrieval_rag.LegacyIndex`] use_dummy_dataset (`bool`, *optional*, defaults to `False`) Whether to load a "dummy" variant of the dataset specified by `dataset`. label_smoothing (`float`, *optional*, defaults to 0.0): Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed. do_marginalize (`bool`, *optional*, defaults to `False`): If `True`, the logits are marginalized over all documents by making use of `torch.nn.functional.log_softmax`. reduce_loss (`bool`, *optional*, defaults to `False`): Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation. do_deduplication (`bool`, *optional*, defaults to `True`): Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to `False` if used while training with distributed backend. exclude_bos_score (`bool`, *optional*, defaults to `False`): Whether or not to disregard the BOS token when computing the loss. output_retrieved(`bool`, *optional*, defaults to `False`): If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and `context_attention_mask` are returned. See returned tensors for more detail. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). forced_eos_token_id (`int`, *optional*): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`. ''' @add_start_docstrings(__a ) class lowercase( __a ): '''simple docstring''' lowercase__ = "rag" lowercase__ = True def __init__( self: Union[str, Any], a_: int=None, a_: Tuple=True, a_: Optional[int]=None, a_: List[str]=None, a_: int=None, a_: Optional[Any]=None, a_: List[str]=None, a_: Optional[Any]=" / ", a_: Tuple=" // ", a_: List[Any]=5, a_: Dict=300, a_: Tuple=768, a_: Optional[Any]=8, a_: int="wiki_dpr", a_: Any="train", a_: Optional[int]="compressed", a_: Optional[int]=None, a_: List[Any]=None, a_: Optional[Any]=False, a_: str=False, a_: Dict=0.0, a_: Union[str, Any]=True, a_: Union[str, Any]=False, a_: str=False, a_: List[str]=False, a_: Union[str, Any]=True, a_: Any=None, **a_: List[Any], ): '''simple docstring''' super().__init__( bos_token_id=a_, pad_token_id=a_, eos_token_id=a_, decoder_start_token_id=a_, forced_eos_token_id=a_, is_encoder_decoder=a_, prefix=a_, vocab_size=a_, **a_, ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _snake_case : Union[str, Any] = kwargs.pop("""question_encoder""" ) _snake_case : List[str] = question_encoder_config.pop("""model_type""" ) _snake_case : Union[str, Any] = kwargs.pop("""generator""" ) _snake_case : Any = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig _snake_case : Union[str, Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Optional[Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Any = reduce_loss _snake_case : Optional[int] = label_smoothing _snake_case : Dict = exclude_bos_score _snake_case : int = do_marginalize _snake_case : Optional[Any] = title_sep _snake_case : Any = doc_sep _snake_case : List[str] = n_docs _snake_case : Tuple = max_combined_length _snake_case : Optional[Any] = dataset _snake_case : Union[str, Any] = dataset_split _snake_case : Tuple = index_name _snake_case : Any = retrieval_vector_size _snake_case : Union[str, Any] = retrieval_batch_size _snake_case : str = passages_path _snake_case : Tuple = index_path _snake_case : List[Any] = use_dummy_dataset _snake_case : Optional[Any] = output_retrieved _snake_case : Tuple = do_deduplication _snake_case : Union[str, Any] = use_cache if self.forced_eos_token_id is None: _snake_case : Dict = getattr(self.generator, """forced_eos_token_id""", a_ ) @classmethod def UpperCamelCase_ ( cls: Any, a_: PretrainedConfig, a_: PretrainedConfig, **a_: Optional[Any] ): '''simple docstring''' return cls(question_encoder=question_encoder_config.to_dict(), generator=generator_config.to_dict(), **a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Optional[int] = copy.deepcopy(self.__dict__ ) _snake_case : List[str] = self.question_encoder.to_dict() _snake_case : Tuple = self.generator.to_dict() _snake_case : Dict = self.__class__.model_type return output
64
1
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset from utils import logger class lowercase( __a ): '''simple docstring''' def __init__( self: Any, a_: Any, a_: Tuple ): '''simple docstring''' _snake_case : Any = params _snake_case : int = np.array(a_ ) _snake_case : str = np.array([len(a_ ) 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[str], a_: Dict ): '''simple docstring''' return (self.token_ids[index], self.lengths[index]) def __len__( self: Optional[Any] ): '''simple docstring''' return len(self.lengths ) def UpperCamelCase_ ( self: List[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 UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Union[str, Any] = self.params.max_model_input_size _snake_case : str = self.lengths > max_len logger.info(f"Splitting {sum(a_ )} too long sequences." ) def divide_chunks(a_: Tuple, a_: int ): return [l[i : i + n] for i in range(0, len(a_ ), a_ )] _snake_case : List[Any] = [] _snake_case : Optional[int] = [] if self.params.mlm: _snake_case , _snake_case : Optional[int] = self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""] else: _snake_case , _snake_case : Optional[int] = 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: _snake_case : Optional[Any] = [] for sub_s in divide_chunks(seq_, max_len - 2 ): if sub_s[0] != cls_id: _snake_case : Optional[int] = np.insert(a_, 0, a_ ) if sub_s[-1] != sep_id: _snake_case : List[Any] = np.insert(a_, len(a_ ), a_ ) assert len(a_ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(a_ ) new_tok_ids.extend(a_ ) new_lengths.extend([len(a_ ) for l in sub_seqs] ) _snake_case : Union[str, Any] = np.array(a_ ) _snake_case : List[Any] = np.array(a_ ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' _snake_case : Optional[int] = len(self ) _snake_case : int = self.lengths > 11 _snake_case : str = self.token_ids[indices] _snake_case : int = self.lengths[indices] _snake_case : int = len(self ) logger.info(f"Remove {init_size - new_size} too short (<=11 tokens) sequences." ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' if "unk_token" not in self.params.special_tok_ids: return else: _snake_case : Dict = self.params.special_tok_ids["""unk_token"""] _snake_case : Optional[int] = len(self ) _snake_case : List[str] = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) _snake_case : Dict = (unk_occs / self.lengths) < 0.5 _snake_case : int = self.token_ids[indices] _snake_case : Optional[Any] = self.lengths[indices] _snake_case : Dict = len(self ) logger.info(f"Remove {init_size - new_size} sequences with a high level of unknown tokens (50%)." ) def UpperCamelCase_ ( self: Any ): '''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 UpperCamelCase_ ( self: Dict, a_: Optional[int] ): '''simple docstring''' _snake_case : Optional[Any] = [t[0] for t in batch] _snake_case : int = [t[1] for t in batch] assert len(a_ ) == len(a_ ) # Max for paddings _snake_case : int = max(a_ ) # Pad token ids if self.params.mlm: _snake_case : Any = self.params.special_tok_ids["""pad_token"""] else: _snake_case : Optional[Any] = self.params.special_tok_ids["""unk_token"""] _snake_case : Dict = [list(t.astype(a_ ) ) + [pad_idx] * (max_seq_len_ - len(a_ )) for t in token_ids] assert len(tk_ ) == len(a_ ) assert all(len(a_ ) == max_seq_len_ for t in tk_ ) _snake_case : List[str] = torch.tensor(tk_ ) # (bs, max_seq_len_) _snake_case : Optional[Any] = torch.tensor(a_ ) # (bs) return tk_t, lg_t
64
"""simple docstring""" import os from typing import Dict, List, Tuple, TypeVar, Union A_ = TypeVar('''T''') A_ = Union[List[T], Tuple[T, ...]] A_ = Union[T, List[T], Dict[str, T]] A_ = Union[str, bytes, os.PathLike]
64
1
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase( __a , __a , unittest.TestCase ): '''simple docstring''' lowercase__ = StableDiffusionDiffEditPipeline lowercase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"} lowercase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"} lowercase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase__ = frozenset([] ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' torch.manual_seed(0 ) _snake_case : Dict = 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, attention_head_dim=(2, 4), use_linear_projection=a_, ) _snake_case : str = DDIMScheduler( beta_start=0.00_085, beta_end=0.012, beta_schedule="""scaled_linear""", clip_sample=a_, set_alpha_to_one=a_, ) _snake_case : str = DDIMInverseScheduler( beta_start=0.00_085, beta_end=0.012, beta_schedule="""scaled_linear""", clip_sample=a_, set_alpha_to_zero=a_, ) torch.manual_seed(0 ) _snake_case : Optional[Any] = 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, sample_size=128, ) torch.manual_seed(0 ) _snake_case : List[str] = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=32, intermediate_size=37, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_000, hidden_act="""gelu""", projection_dim=512, ) _snake_case : Optional[int] = CLIPTextModel(a_ ) _snake_case : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _snake_case : str = { """unet""": unet, """scheduler""": scheduler, """inverse_scheduler""": inverse_scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self: Optional[Any], a_: Any, a_: Any=0 ): '''simple docstring''' _snake_case : List[str] = floats_tensor((1, 16, 16), rng=random.Random(a_ ) ).to(a_ ) _snake_case : Dict = floats_tensor((1, 2, 4, 16, 16), rng=random.Random(a_ ) ).to(a_ ) if str(a_ ).startswith("""mps""" ): _snake_case : Optional[int] = torch.manual_seed(a_ ) else: _snake_case : List[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) _snake_case : Dict = { """prompt""": """a dog and a newt""", """mask_image""": mask, """image_latents""": latents, """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self: Any, a_: Dict, a_: List[Any]=0 ): '''simple docstring''' _snake_case : str = floats_tensor((1, 3, 32, 32), rng=random.Random(a_ ) ).to(a_ ) _snake_case : str = image.cpu().permute(0, 2, 3, 1 )[0] _snake_case : Dict = Image.fromarray(np.uinta(a_ ) ).convert("""RGB""" ) if str(a_ ).startswith("""mps""" ): _snake_case : str = torch.manual_seed(a_ ) else: _snake_case : Dict = torch.Generator(device=a_ ).manual_seed(a_ ) _snake_case : int = { """image""": image, """source_prompt""": """a cat and a frog""", """target_prompt""": """a dog and a newt""", """generator""": generator, """num_inference_steps""": 2, """num_maps_per_mask""": 2, """mask_encode_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self: Any, a_: int, a_: Optional[Any]=0 ): '''simple docstring''' _snake_case : Tuple = floats_tensor((1, 3, 32, 32), rng=random.Random(a_ ) ).to(a_ ) _snake_case : Optional[Any] = image.cpu().permute(0, 2, 3, 1 )[0] _snake_case : List[str] = Image.fromarray(np.uinta(a_ ) ).convert("""RGB""" ) if str(a_ ).startswith("""mps""" ): _snake_case : int = torch.manual_seed(a_ ) else: _snake_case : Union[str, Any] = torch.Generator(device=a_ ).manual_seed(a_ ) _snake_case : Dict = { """image""": image, """prompt""": """a cat and a frog""", """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """decode_latents""": True, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self: str ): '''simple docstring''' if not hasattr(self.pipeline_class, """_optional_components""" ): return _snake_case : Optional[int] = self.get_dummy_components() _snake_case : Optional[int] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a_, a_, a_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) _snake_case : Optional[int] = self.get_dummy_inputs(a_ ) _snake_case : Optional[Any] = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) _snake_case : int = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(a_, a_ ) is None, f"`{optional_component}` did not stay set to None after loading.", ) _snake_case : Tuple = self.get_dummy_inputs(a_ ) _snake_case : Tuple = pipe_loaded(**a_ )[0] _snake_case : List[str] = np.abs(output - output_loaded ).max() self.assertLess(a_, 1E-4 ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : List[str] = """cpu""" _snake_case : Optional[int] = self.get_dummy_components() _snake_case : Dict = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : int = self.get_dummy_mask_inputs(a_ ) _snake_case : Union[str, Any] = pipe.generate_mask(**a_ ) _snake_case : Union[str, Any] = mask[0, -3:, -3:] self.assertEqual(mask.shape, (1, 16, 16) ) _snake_case : Tuple = np.array([0] * 9 ) _snake_case : str = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_, 1E-3 ) self.assertEqual(mask[0, -3, -4], 0 ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : int = """cpu""" _snake_case : Union[str, Any] = self.get_dummy_components() _snake_case : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : List[str] = self.get_dummy_inversion_inputs(a_ ) _snake_case : str = pipe.invert(**a_ ).images _snake_case : List[str] = image[0, -1, -3:, -3:] self.assertEqual(image.shape, (2, 32, 32, 3) ) _snake_case : List[Any] = np.array( [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799], ) _snake_case : Optional[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_, 1E-3 ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' _snake_case : Any = """cpu""" _snake_case : List[Any] = self.get_dummy_components() _snake_case : str = {"""beta_start""": 0.00_085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""} _snake_case : Dict = DPMSolverMultistepScheduler(**a_ ) _snake_case : Any = DPMSolverMultistepInverseScheduler(**a_ ) _snake_case : Optional[Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : List[Any] = self.get_dummy_inversion_inputs(a_ ) _snake_case : Union[str, Any] = pipe.invert(**a_ ).images _snake_case : List[str] = image[0, -1, -3:, -3:] self.assertEqual(image.shape, (2, 32, 32, 3) ) _snake_case : int = np.array( [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799], ) _snake_case : Tuple = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_, 1E-3 ) @require_torch_gpu @slow class lowercase( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def UpperCamelCase_ ( cls: Dict ): '''simple docstring''' _snake_case : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""" ) _snake_case : Optional[Any] = raw_image.convert("""RGB""" ).resize((768, 768) ) _snake_case : Optional[Any] = raw_image def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : Tuple = torch.manual_seed(0 ) _snake_case : Optional[int] = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""", safety_checker=a_, torch_dtype=torch.floataa ) _snake_case : Any = DDIMScheduler.from_config(pipe.scheduler.config ) _snake_case : Optional[Any] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) _snake_case : Optional[Any] = """a bowl of fruit""" _snake_case : Union[str, Any] = """a bowl of pears""" _snake_case : List[str] = pipe.generate_mask( image=self.raw_image, source_prompt=a_, target_prompt=a_, generator=a_, ) _snake_case : Optional[Any] = pipe.invert( prompt=a_, image=self.raw_image, inpaint_strength=0.7, generator=a_ ).latents _snake_case : Dict = pipe( prompt=a_, mask_image=a_, image_latents=a_, generator=a_, negative_prompt=a_, inpaint_strength=0.7, output_type="""numpy""", ).images[0] _snake_case : Union[str, Any] = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' _snake_case : Tuple = torch.manual_seed(0 ) _snake_case : List[Any] = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""", safety_checker=a_, torch_dtype=torch.floataa ) _snake_case : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) _snake_case : Any = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) _snake_case : Tuple = """a bowl of fruit""" _snake_case : Optional[Any] = """a bowl of pears""" _snake_case : Any = pipe.generate_mask( image=self.raw_image, source_prompt=a_, target_prompt=a_, generator=a_, ) _snake_case : Optional[int] = pipe.invert( prompt=a_, image=self.raw_image, inpaint_strength=0.7, generator=a_, num_inference_steps=25, ).latents _snake_case : Optional[Any] = pipe( prompt=a_, mask_image=a_, image_latents=a_, generator=a_, negative_prompt=a_, inpaint_strength=0.7, num_inference_steps=25, output_type="""numpy""", ).images[0] _snake_case : str = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] _snake_case : List[Any] = [] def generate(snake_case__ : int , snake_case__ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even _snake_case , _snake_case : Optional[Any] = arr[k - 1], arr[i] else: # k is odd _snake_case , _snake_case : List[str] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
64
1
"""simple docstring""" import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , **snake_case__ : Tuple ): """simple docstring""" _snake_case : List[Any] = AutoConfig.from_pretrained(snake_case__ , **snake_case__ ) _snake_case : Dict = AutoModelForSeqaSeqLM.from_config(snake_case__ ) model.save_pretrained(snake_case__ ) AutoTokenizer.from_pretrained(snake_case__ ).save_pretrained(snake_case__ ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
64
"""simple docstring""" from math import factorial A_ = {str(d): factorial(d) for d in range(10)} def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , snake_case__ ) if sum_of_digit_factorial(snake_case__ ) == i ) if __name__ == "__main__": print(F'''{solution() = }''')
64
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" stooge(snake_case__ , 0 , len(snake_case__ ) - 1 ) return arr def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int ): """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _snake_case , _snake_case : Tuple = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _snake_case : Dict = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case__ , i + t , (snake_case__) ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(stooge_sort(unsorted))
64
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : int ): """simple docstring""" if len(snake_case__ ) < k or k < 0: raise ValueError("""Invalid Input""" ) _snake_case : Optional[int] = sum(array[:k] ) for i in range(len(snake_case__ ) - k ): _snake_case : Optional[Any] = current_sum - array[i] + array[i + k] _snake_case : List[str] = max(snake_case__ , snake_case__ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() A_ = [randint(-10_00, 10_00) for i in range(1_00)] A_ = randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
64
1
"""simple docstring""" import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def UpperCAmelCase__ (): """simple docstring""" assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = """mock-s3-bucket""" _snake_case : Any = F"s3://{mock_bucket}" _snake_case : List[str] = extract_path_from_uri(snake_case__ ) assert dataset_path.startswith("""s3://""" ) is False _snake_case : int = """./local/path""" _snake_case : List[Any] = extract_path_from_uri(snake_case__ ) assert dataset_path == new_dataset_path def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" _snake_case : Optional[int] = is_remote_filesystem(snake_case__ ) assert is_remote is True _snake_case : Any = fsspec.filesystem("""file""" ) _snake_case : Tuple = is_remote_filesystem(snake_case__ ) assert is_remote is False @pytest.mark.parametrize("""compression_fs_class""" , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Optional[Any] , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : int , snake_case__ : List[Any] , snake_case__ : Dict ): """simple docstring""" _snake_case : Dict = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_file, """bz2""": bza_file, """lz4""": lza_file} _snake_case : int = input_paths[compression_fs_class.protocol] if input_path is None: _snake_case : List[Any] = F"for '{compression_fs_class.protocol}' compression protocol, " if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(snake_case__ ) _snake_case : Any = fsspec.filesystem(compression_fs_class.protocol , fo=snake_case__ ) assert isinstance(snake_case__ , snake_case__ ) _snake_case : Optional[int] = os.path.basename(snake_case__ ) _snake_case : Dict = expected_filename[: expected_filename.rindex(""".""" )] assert fs.glob("""*""" ) == [expected_filename] with fs.open(snake_case__ , """r""" , encoding="""utf-8""" ) as f, open(snake_case__ , encoding="""utf-8""" ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("""protocol""" , ["""zip""", """gzip"""] ) def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Any , snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case : Any = {"""zip""": zip_jsonl_path, """gzip""": jsonl_gz_path} _snake_case : Union[str, Any] = compressed_file_paths[protocol] _snake_case : Union[str, Any] = """dataset.jsonl""" _snake_case : Union[str, Any] = F"{protocol}://{member_file_path}::{compressed_file_path}" _snake_case , *_snake_case : str = fsspec.get_fs_token_paths(snake_case__ ) assert fs.isfile(snake_case__ ) assert not fs.isfile("""non_existing_""" + member_file_path ) @pytest.mark.integration def UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : str , snake_case__ : Any , snake_case__ : Any ): """simple docstring""" _snake_case : Tuple = hf_api.dataset_info(snake_case__ , token=snake_case__ ) _snake_case : Optional[Any] = HfFileSystem(repo_info=snake_case__ , token=snake_case__ ) assert sorted(hffs.glob("""*""" ) ) == [".gitattributes", "data"] assert hffs.isdir("""data""" ) assert hffs.isfile(""".gitattributes""" ) and hffs.isfile("""data/text_data.txt""" ) with open(snake_case__ ) as f: assert hffs.open("""data/text_data.txt""" , """r""" ).read() == f.read() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Optional[int] = """bz2""" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(snake_case__ , snake_case__ , clobber=snake_case__ ) with pytest.warns(snake_case__ ) as warning_info: importlib.reload(datasets.filesystems ) assert len(snake_case__ ) == 1 assert ( str(warning_info[0].message ) == F"A filesystem protocol was already set for {protocol} and will be overwritten." )
64
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } A_ = { '''yjernite/retribert-base-uncased''': 5_12, } A_ = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = RetriBertTokenizer lowercase__ = ["input_ids", "attention_mask"] def __init__( self: int, a_: int=None, a_: Dict=None, a_: Any=True, a_: int="[UNK]", a_: Any="[SEP]", a_: List[Any]="[PAD]", a_: List[Any]="[CLS]", a_: str="[MASK]", a_: Dict=True, a_: Optional[int]=None, **a_: Tuple, ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Dict = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : List[Any] = do_lower_case _snake_case : List[str] = strip_accents _snake_case : Tuple = tokenize_chinese_chars _snake_case : Tuple = normalizer_class(**a_ ) _snake_case : List[str] = do_lower_case def UpperCamelCase_ ( self: Any, a_: str, a_: Optional[int]=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: List[str], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: Dict, a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : Union[str, Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : int ): """simple docstring""" if len(snake_case__ ) == 0: return False _snake_case : Dict = len(snake_case__ ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , snake_case__ ) else: return binary_search(a_list[midpoint + 1 :] , snake_case__ ) if __name__ == "__main__": A_ = input('''Enter numbers separated by comma:\n''').strip() A_ = [int(item.strip()) for item in user_input.split(''',''')] A_ = int(input('''Enter the number to be found in the list:\n''').strip()) A_ = '''''' if binary_search(sequence, target) else '''not ''' print(F'''{target} was {not_str}found in {sequence}''')
64
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CodeGenTokenizer lowercase__ = CodeGenTokenizerFast lowercase__ = True lowercase__ = {"add_prefix_space": True} lowercase__ = False def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _snake_case : Tuple = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] _snake_case : Tuple = dict(zip(a_, range(len(a_ ) ) ) ) _snake_case : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _snake_case : List[Any] = {"""unk_token""": """<unk>"""} _snake_case : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) _snake_case : Optional[Any] = 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(a_ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(a_ ) ) def UpperCamelCase_ ( self: Any, **a_: int ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Any, **a_: str ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Dict ): '''simple docstring''' _snake_case : Union[str, Any] = """lower newer""" _snake_case : Tuple = """lower newer""" return input_text, output_text def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) _snake_case : Optional[Any] = """lower newer""" _snake_case : Optional[int] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] _snake_case : int = tokenizer.tokenize(a_, add_prefix_space=a_ ) self.assertListEqual(a_, a_ ) _snake_case : str = tokens + [tokenizer.unk_token] _snake_case : Optional[int] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : int = self.get_tokenizer() _snake_case : int = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : Dict = """lower newer""" # Testing tokenization _snake_case : Dict = tokenizer.tokenize(a_, add_prefix_space=a_ ) _snake_case : List[str] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids without special tokens _snake_case : Optional[Any] = tokenizer.encode(a_, add_special_tokens=a_, add_prefix_space=a_ ) _snake_case : Tuple = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids with special tokens _snake_case : Tuple = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : int = tokenizer.encode(a_, add_prefix_space=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) # Testing the unknown token _snake_case : Tuple = tokens + [rust_tokenizer.unk_token] _snake_case : List[Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Dict, *a_: Dict, **a_: int ): '''simple docstring''' pass def UpperCamelCase_ ( self: int, a_: List[Any]=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : List[Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) # Simple input _snake_case : Any = """This is a simple input""" _snake_case : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Optional[int] = ("""This is a simple input""", """This is a pair""") _snake_case : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) # Pair input self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token="""<pad>""" ) # Simple input _snake_case : List[Any] = """This is a simple input""" _snake_case : int = ["""This is a simple input looooooooong""", """This is a simple input"""] _snake_case : Any = ("""This is a simple input""", """This is a pair""") _snake_case : str = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] _snake_case : str = tokenizer.pad_token_id _snake_case : Optional[int] = tokenizer(a_, padding="""max_length""", max_length=30, return_tensors="""np""" ) _snake_case : Dict = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) _snake_case : Tuple = tokenizer(*a_, padding="""max_length""", max_length=60, return_tensors="""np""" ) _snake_case : Optional[Any] = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Tuple = """$$$""" _snake_case : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=a_, add_bos_token=a_ ) _snake_case : str = """This is a simple input""" _snake_case : int = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Tuple = tokenizer(a_ ) _snake_case : Optional[Any] = tokenizer(a_ ) self.assertEqual(out_s.input_ids[0], a_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) _snake_case : Optional[int] = tokenizer.decode(out_s.input_ids ) _snake_case : int = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], a_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) _snake_case : Dict = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" _snake_case : Union[str, Any] = """\nif len_a > len_b: result = a\nelse: result = b""" _snake_case : Optional[Any] = tokenizer.encode(a_ ) _snake_case : Dict = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] _snake_case : Optional[Any] = tokenizer.decode(a_, truncate_before_pattern=a_ ) self.assertEqual(a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' pass
64
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all MVP models at https://huggingface.co/models?filter=mvp A_ = { '''vocab_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''', }, '''added_tokens.json''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''', }, '''merges_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json''', }, } A_ = { '''RUCAIBox/mvp''': 10_24, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] lowercase__ = MvpTokenizer def __init__( self: Optional[int], a_: Dict=None, a_: Any=None, a_: List[str]=None, a_: Any="replace", a_: str="<s>", a_: int="</s>", a_: Optional[int]="</s>", a_: int="<s>", a_: int="<unk>", a_: Dict="<pad>", a_: List[Any]="<mask>", a_: int=False, a_: Tuple=True, **a_: Any, ): '''simple docstring''' super().__init__( a_, a_, tokenizer_file=a_, errors=a_, bos_token=a_, eos_token=a_, sep_token=a_, cls_token=a_, unk_token=a_, pad_token=a_, mask_token=a_, add_prefix_space=a_, trim_offsets=a_, **a_, ) _snake_case : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : str = getattr(a_, pre_tok_state.pop("""type""" ) ) _snake_case : List[Any] = add_prefix_space _snake_case : Dict = pre_tok_class(**a_ ) _snake_case : Dict = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _snake_case : Dict = """post_processor""" _snake_case : Union[str, Any] = getattr(self.backend_tokenizer, a_, a_ ) if tokenizer_component_instance: _snake_case : List[Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _snake_case : Optional[int] = tuple(state["""sep"""] ) if "cls" in state: _snake_case : Tuple = tuple(state["""cls"""] ) _snake_case : List[str] = False if state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : List[Any] = add_prefix_space _snake_case : int = True if state.get("""trim_offsets""", a_ ) != trim_offsets: _snake_case : Tuple = trim_offsets _snake_case : List[Any] = True if changes_to_apply: _snake_case : str = getattr(a_, state.pop("""type""" ) ) _snake_case : Optional[Any] = component_class(**a_ ) setattr(self.backend_tokenizer, a_, a_ ) @property def UpperCamelCase_ ( self: str ): '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def UpperCamelCase_ ( self: Optional[Any], a_: Optional[Any] ): '''simple docstring''' _snake_case : List[Any] = AddedToken(a_, lstrip=a_, rstrip=a_ ) if isinstance(a_, a_ ) else value _snake_case : Tuple = value def UpperCamelCase_ ( self: Optional[int], *a_: Union[str, Any], **a_: List[str] ): '''simple docstring''' _snake_case : Any = kwargs.get("""is_split_into_words""", a_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], *a_: Optional[Any], **a_: str ): '''simple docstring''' _snake_case : Optional[Any] = kwargs.get("""is_split_into_words""", a_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " """to use it with pretokenized inputs.""" ) return super()._encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : str = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ ) def UpperCamelCase_ ( self: Tuple, a_: Optional[Any], a_: str=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCamelCase_ ( self: Union[str, Any], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : int = [self.sep_token_id] _snake_case : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
64
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser A_ = re.compile(r'''\s+''') def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" return {"hash": hashlib.mda(re.sub(snake_case__ , """""" , example["""content"""] ).encode("""utf-8""" ) ).hexdigest()} def UpperCAmelCase__ (snake_case__ : Dict ): """simple docstring""" _snake_case : Any = [len(snake_case__ ) for line in example["""content"""].splitlines()] return {"line_mean": np.mean(snake_case__ ), "line_max": max(snake_case__ )} def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" _snake_case : Tuple = np.mean([c.isalnum() for c in example["""content"""]] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : List[Any] ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example["""hash"""] ) return True else: return False def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : List[str]=5 ): """simple docstring""" _snake_case : Any = ["""auto-generated""", """autogenerated""", """automatically generated"""] _snake_case : Tuple = example["""content"""].splitlines() for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Union[str, Any]=5 , snake_case__ : Any=0.05 ): """simple docstring""" _snake_case : Optional[Any] = ["""unit tests""", """test file""", """configuration file"""] _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : Dict = 0 _snake_case : str = 0 # first test for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _snake_case : Optional[int] = example["""content"""].count("""\n""" ) _snake_case : Tuple = int(coeff * nlines ) for line in lines: count_config += line.lower().count("""config""" ) count_test += line.lower().count("""test""" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Optional[int] = ["""def """, """class """, """for """, """while """] _snake_case : str = example["""content"""].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : List[str]=4 ): """simple docstring""" _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : str = 0 for line in lines: counter += line.lower().count("""=""" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase__ (snake_case__ : List[str] ): """simple docstring""" _snake_case : Optional[Any] = tokenizer(example["""content"""] , truncation=snake_case__ )["""input_ids"""] _snake_case : Optional[Any] = len(example["""content"""] ) / len(snake_case__ ) return {"ratio": ratio} def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[int] = {} results.update(get_hash(snake_case__ ) ) results.update(line_stats(snake_case__ ) ) results.update(alpha_stats(snake_case__ ) ) results.update(char_token_ratio(snake_case__ ) ) results.update(is_autogenerated(snake_case__ ) ) results.update(is_config_or_test(snake_case__ ) ) results.update(has_no_keywords(snake_case__ ) ) results.update(has_few_assignments(snake_case__ ) ) return results def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : List[str] ): """simple docstring""" if not check_uniques(snake_case__ , snake_case__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" with open(snake_case__ , """rb""" ) as f_in: with gzip.open(str(snake_case__ ) + """.gz""" , """wb""" , compresslevel=6 ) as f_out: shutil.copyfileobj(snake_case__ , snake_case__ ) os.unlink(snake_case__ ) # Settings A_ = HfArgumentParser(PreprocessingArguments) A_ = parser.parse_args() if args.num_workers is None: A_ = multiprocessing.cpu_count() A_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset A_ = time.time() A_ = load_dataset(args.dataset_name, split='''train''') print(F'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing A_ = time.time() A_ = ds.map(preprocess, num_proc=args.num_workers) print(F'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes A_ = set(ds.unique('''hash''')) A_ = len(uniques) / len(ds) print(F'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics A_ = time.time() A_ = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F'''Time to filter dataset: {time.time()-t_start:.2f}''') print(F'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: A_ = time.time() A_ , A_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(F'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file A_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) A_ = output_dir / '''data''' data_dir.mkdir(exist_ok=True) A_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): A_ = str(data_dir / F'''file-{file_number+1:012}.json''') A_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'''Time to save dataset: {time.time()-t_start:.2f}''')
64
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list[int] ): """simple docstring""" _snake_case : Optional[Any] = [] if len(snake_case__ ) == 1: return [nums.copy()] for _ in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = nums.pop(0 ) _snake_case : Any = permute(snake_case__ ) for perm in permutations: perm.append(snake_case__ ) result.extend(snake_case__ ) nums.append(snake_case__ ) return result def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" def backtrack(snake_case__ : List[str] ): if start == len(snake_case__ ) - 1: output.append(nums[:] ) else: for i in range(snake_case__ , len(snake_case__ ) ): _snake_case , _snake_case : Any = nums[i], nums[start] backtrack(start + 1 ) _snake_case , _snake_case : Optional[int] = nums[i], nums[start] # backtrack _snake_case : Any = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function A_ = permutea([1, 2, 3]) print(res) doctest.testmod()
64
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase( unittest.TestCase ): '''simple docstring''' @property def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Any = ort.SessionOptions() _snake_case : Union[str, Any] = False return options def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _snake_case : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _snake_case : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _snake_case : Optional[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""", revision="""onnx""", safety_checker=a_, feature_extractor=a_, provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : Optional[Any] = """A red cat sitting on a park bench""" _snake_case : Optional[int] = np.random.RandomState(0 ) _snake_case : Any = pipe( prompt=a_, image=a_, mask_image=a_, strength=0.75, guidance_scale=7.5, num_inference_steps=15, generator=a_, output_type="""np""", ) _snake_case : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
64
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" if not isinstance(snake_case__ , snake_case__ ) or number < 0: raise ValueError("""Input must be a non-negative integer""" ) _snake_case : str = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
64
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() A_ = logging.get_logger(__name__) A_ = { '''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''', '''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''', } A_ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Dict , snake_case__ : Any , snake_case__ : str , snake_case__ : str ): """simple docstring""" for attribute in key.split(""".""" ): _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ) if weight_type is not None: _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ).shape else: _snake_case : Optional[Any] = hf_pointer.shape assert hf_shape == value.shape, ( 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": _snake_case : int = value elif weight_type == "weight_g": _snake_case : str = value elif weight_type == "weight_v": _snake_case : Tuple = value elif weight_type == "bias": _snake_case : List[str] = value else: _snake_case : int = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str] ): """simple docstring""" _snake_case : List[Any] = [] _snake_case : Optional[Any] = fairseq_model.state_dict() _snake_case : str = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _snake_case : Optional[Any] = None for name, value in fairseq_dict.items(): _snake_case : Optional[Any] = False if "conv_layers" in name: load_conv_layer( snake_case__ , snake_case__ , snake_case__ , snake_case__ , hf_model.config.feat_extract_norm == """group""" , ) _snake_case : Dict = True elif name.split(""".""" )[0] == "proj": _snake_case : Dict = fairseq_model.proj _snake_case : Optional[int] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _snake_case : Dict = True if "*" in mapped_key: _snake_case : Optional[int] = name.split(snake_case__ )[0].split(""".""" )[-2] _snake_case : Union[str, Any] = mapped_key.replace("""*""" , snake_case__ ) if "weight_g" in name: _snake_case : str = """weight_g""" elif "weight_v" in name: _snake_case : Optional[Any] = """weight_v""" elif "bias" in name: _snake_case : Union[str, Any] = """bias""" elif "weight" in name: _snake_case : int = """weight""" else: _snake_case : Optional[int] = None set_recursively(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) continue if not is_used: unused_weights.append(snake_case__ ) logger.warning(F"Unused weights: {unused_weights}" ) return proj_weight def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : int ): """simple docstring""" _snake_case : Any = full_name.split("""conv_layers.""" )[-1] _snake_case : Optional[int] = name.split(""".""" ) _snake_case : List[str] = int(items[0] ) _snake_case : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _snake_case : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _snake_case : List[Any] = 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _snake_case : int = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _snake_case : List[str] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case , _snake_case : Optional[Any] = emb.weight.shape _snake_case : Optional[int] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _snake_case : Union[str, Any] = emb.weight.data return lin_layer def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" with open(snake_case__ , """r""" , encoding="""utf-8""" ) as f: _snake_case : Any = f.readlines() _snake_case : Optional[Any] = [line.split(""" """ )[0] for line in lines] _snake_case : str = len(snake_case__ ) _snake_case : Tuple = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(snake_case__ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def UpperCAmelCase__ (snake_case__ : int , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Dict , snake_case__ : List[Any] , snake_case__ : str , snake_case__ : Union[str, Any] , ): """simple docstring""" _snake_case : Optional[int] = WavaVecaConfig.from_pretrained(snake_case__ ) _snake_case : List[str] = SpeechaTextaConfig.from_pretrained( snake_case__ , vocab_size=snake_case__ , decoder_layers=snake_case__ , do_stable_layer_norm=snake_case__ ) _snake_case : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case__ , return_attention_mask=snake_case__ , ) _snake_case , _snake_case , _snake_case : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) _snake_case : Optional[Any] = model[0].eval() # set weights for wav2vec2 encoder _snake_case : Any = WavaVecaModel(snake_case__ ) _snake_case : Optional[Any] = recursively_load_weights_wavaveca(model.encoder , snake_case__ ) _snake_case : Optional[Any] = SpeechaTextaForCausalLM(snake_case__ ) _snake_case , _snake_case : List[str] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case__ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) _snake_case : Any = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(F"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) _snake_case : Any = SpeechEncoderDecoderModel(encoder=snake_case__ , decoder=snake_case__ ) _snake_case : Any = False # add projection layer _snake_case : int = nn.Parameter(projection_layer.weight ) _snake_case : Any = nn.Parameter(projection_layer.bias ) _snake_case : Any = create_vocab_dict(snake_case__ ) with open(os.path.join(snake_case__ , """vocab.json""" ) , """w""" ) as fp: json.dump(snake_case__ , snake_case__ ) _snake_case : Dict = SpeechaTextaTokenizer(os.path.join(snake_case__ , """vocab.json""" ) ) tokenizer.save_pretrained(snake_case__ ) _snake_case : str = hf_wavavec.config.to_dict() _snake_case : List[str] = tokenizer.pad_token_id _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Union[str, Any] = tokenizer.eos_token_id _snake_case : Optional[Any] = """speech_to_text_2""" _snake_case : Optional[int] = """wav2vec2""" _snake_case : Tuple = SpeechEncoderDecoderConfig.from_dict(snake_case__ ) hf_wavavec.save_pretrained(snake_case__ ) feature_extractor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = 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( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=1_02_24, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') A_ = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
64
1
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : float ): """simple docstring""" return 10 - x * x def UpperCAmelCase__ (snake_case__ : float , snake_case__ : float ): """simple docstring""" if equation(snake_case__ ) * equation(snake_case__ ) >= 0: raise ValueError("""Wrong space!""" ) _snake_case : Tuple = a while (b - a) >= 0.01: # Find middle point _snake_case : Optional[Any] = (a + b) / 2 # Check if middle point is root if equation(snake_case__ ) == 0.0: break # Decide the side to repeat the steps if equation(snake_case__ ) * equation(snake_case__ ) < 0: _snake_case : Optional[int] = c else: _snake_case : Tuple = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
64
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A_ = 16 A_ = 32 def UpperCAmelCase__ (snake_case__ : Accelerator , snake_case__ : int = 16 ): """simple docstring""" _snake_case : Optional[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _snake_case : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(snake_case__ : Any ): # max_length=None => use the model max length (it's actually the default) _snake_case : Any = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _snake_case : List[Any] = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case : int = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _snake_case : Optional[int] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _snake_case : str = 16 elif accelerator.mixed_precision != "no": _snake_case : Optional[int] = 8 else: _snake_case : Optional[int] = None return tokenizer.pad( snake_case__ , padding="""longest""" , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _snake_case : Optional[int] = DataLoader( tokenized_datasets["""train"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) _snake_case : Dict = DataLoader( tokenized_datasets["""validation"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders A_ = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any ): """simple docstring""" if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , snake_case__ ) == "1": _snake_case : List[Any] = 2 # Initialize accelerator _snake_case : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case : Tuple = config["""lr"""] _snake_case : str = int(config["""num_epochs"""] ) _snake_case : Union[str, Any] = int(config["""seed"""] ) _snake_case : Union[str, Any] = int(config["""batch_size"""] ) _snake_case : List[str] = evaluate.load("""glue""" , """mrpc""" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case__ ) def inner_training_loop(snake_case__ : Union[str, Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case : List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _snake_case : Tuple = model.to(accelerator.device ) # Instantiate optimizer _snake_case : str = AdamW(params=model.parameters() , lr=snake_case__ ) _snake_case , _snake_case : Optional[int] = get_dataloaders(snake_case__ , snake_case__ ) # Instantiate scheduler _snake_case : str = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=1_00 , num_training_steps=(len(snake_case__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : List[str] = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _snake_case : int = model(**snake_case__ ) _snake_case : str = outputs.loss accelerator.backward(snake_case__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _snake_case : int = model(**snake_case__ ) _snake_case : Optional[Any] = outputs.logits.argmax(dim=-1 ) _snake_case , _snake_case : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) _snake_case : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , snake_case__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=snake_case__ , default=snake_case__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _snake_case : Dict = parser.parse_args() _snake_case : int = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
64
1
"""simple docstring""" import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging A_ = logging.get_logger(__name__) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Optional[int] , snake_case__ : List[Any] , snake_case__ : int=False ): """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( """Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see""" """ https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation""" """ instructions.""" ) raise if not is_sharded: _snake_case : List[Any] = os.path.abspath(snake_case__ ) logger.info(F"Loading PyTorch weights from {pt_path}" ) _snake_case : List[str] = torch.load(snake_case__ , map_location="""cpu""" ) logger.info(F"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters." ) _snake_case : List[Any] = convert_pytorch_state_dict_to_flax(snake_case__ , snake_case__ ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files _snake_case : Union[str, Any] = convert_pytorch_sharded_state_dict_to_flax(snake_case__ , snake_case__ ) return flax_state_dict def UpperCAmelCase__ (snake_case__ : Tuple[str] , snake_case__ : np.ndarray , snake_case__ : Dict[str, jnp.ndarray] , snake_case__ : str , ): """simple docstring""" def is_key_or_prefix_key_in_dict(snake_case__ : Tuple[str] ) -> bool: return len(set(snake_case__ ) & {key, (model_prefix,) + key} ) > 0 # layer norm _snake_case : Tuple = pt_tuple_key[:-1] + ("""scale""",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(snake_case__ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean _snake_case : Dict = pt_tuple_key[:-1] + ("""mean""",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(snake_case__ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var _snake_case : List[str] = pt_tuple_key[:-1] + ("""var""",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(snake_case__ ): return renamed_pt_tuple_key, pt_tensor # embedding _snake_case : Union[str, Any] = pt_tuple_key[:-1] + ("""embedding""",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(snake_case__ ): return renamed_pt_tuple_key, pt_tensor # conv layer _snake_case : str = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(snake_case__ ): _snake_case : Union[str, Any] = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer _snake_case : List[str] = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(snake_case__ ): _snake_case : Tuple = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight _snake_case : Union[str, Any] = pt_tuple_key[:-1] + ("""weight""",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias _snake_case : Any = pt_tuple_key[:-1] + ("""bias""",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 _snake_case : Union[str, Any] = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): _snake_case : Optional[Any] = pt_tuple_key[-2] + """_g""" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): _snake_case : int = pt_tuple_key[-2] + """_v""" if name is not None: _snake_case : Any = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : Dict ): """simple docstring""" _snake_case : Optional[Any] = {k: v.numpy() for k, v in pt_state_dict.items()} _snake_case : Tuple = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: _snake_case : List[str] = flax_model.params["""params"""] else: _snake_case : List[Any] = flax_model.params _snake_case : List[Any] = flatten_dict(snake_case__ ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: _snake_case : List[str] = flatten_dict(flax_model.params["""batch_stats"""] ) random_flax_state_dict.update(snake_case__ ) _snake_case : Tuple = {} _snake_case : Dict = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(""".""" )[0] for k in pt_state_dict.keys()} ) _snake_case : str = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(""".""" )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _snake_case : Any = tuple(pt_key.split(""".""" ) ) # remove base model prefix if necessary _snake_case : Union[str, Any] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: _snake_case : Any = pt_tuple_key[1:] # Correctly rename weight parameters _snake_case , _snake_case : str = rename_key_and_reshape_tensor( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # add model prefix if necessary _snake_case : List[Any] = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: _snake_case : List[Any] = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " F"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: _snake_case : Any = jnp.asarray(snake_case__ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(snake_case__ , snake_case__ ) continue # also add unexpected weight so that warning is thrown _snake_case : Optional[int] = jnp.asarray(snake_case__ ) else: # also add unexpected weight so that warning is thrown _snake_case : int = jnp.asarray(snake_case__ ) return unflatten_dict(snake_case__ ) def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : Any ): """simple docstring""" import torch # Load the index _snake_case : List[Any] = {} for shard_file in shard_filenames: # load using msgpack utils _snake_case : Tuple = torch.load(snake_case__ ) _snake_case : int = {k: v.numpy() for k, v in pt_state_dict.items()} _snake_case : Optional[int] = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: _snake_case : Optional[int] = flax_model.params["""params"""] _snake_case : Union[str, Any] = flatten_dict(snake_case__ ) random_flax_state_dict.update(flatten_dict(flax_model.params["""batch_stats"""] ) ) else: _snake_case : Dict = flax_model.params _snake_case : Union[str, Any] = flatten_dict(snake_case__ ) _snake_case : int = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(""".""" )[0] for k in pt_state_dict.keys()} ) _snake_case : List[str] = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(""".""" )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _snake_case : Optional[Any] = tuple(pt_key.split(""".""" ) ) # remove base model prefix if necessary _snake_case : Any = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: _snake_case : List[str] = pt_tuple_key[1:] # Correctly rename weight parameters _snake_case , _snake_case : List[str] = rename_key_and_reshape_tensor( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # add model prefix if necessary _snake_case : int = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: _snake_case : List[str] = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " F"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: _snake_case : List[str] = jnp.asarray(snake_case__ ) continue if "var" in flax_key[-1]: _snake_case : int = jnp.asarray(snake_case__ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(snake_case__ , snake_case__ ) continue # also add unexpected weight so that warning is thrown _snake_case : Dict = jnp.asarray(snake_case__ ) else: # also add unexpected weight so that warning is thrown _snake_case : int = jnp.asarray(snake_case__ ) return unflatten_dict(snake_case__ ) def UpperCAmelCase__ (snake_case__ : Optional[int] , snake_case__ : str ): """simple docstring""" _snake_case : List[Any] = os.path.abspath(snake_case__ ) logger.info(F"Loading Flax weights from {flax_checkpoint_path}" ) # import correct flax class _snake_case : List[str] = getattr(snake_case__ , """Flax""" + model.__class__.__name__ ) # load flax weight dict with open(snake_case__ , """rb""" ) as state_f: try: _snake_case : List[Any] = from_bytes(snake_case__ , state_f.read() ) except UnpicklingError: raise EnvironmentError(F"Unable to convert {flax_checkpoint_path} to Flax deserializable object. " ) return load_flax_weights_in_pytorch_model(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Optional[Any] ): """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( """Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see""" """ https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation""" """ instructions.""" ) raise # check if we have bf16 weights _snake_case : Dict = flatten_dict(jax.tree_util.tree_map(lambda snake_case__ : x.dtype == jnp.bfloataa , snake_case__ ) ).values() if any(snake_case__ ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( """Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` """ """before loading those in PyTorch model.""" ) _snake_case : Union[str, Any] = jax.tree_util.tree_map( lambda snake_case__ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , snake_case__ ) _snake_case : List[Any] = flatten_dict(snake_case__ ) _snake_case : Optional[Any] = pt_model.state_dict() _snake_case : Tuple = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split(""".""" )[0] for k in pt_model_dict.keys()} ) _snake_case : Tuple = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split(""".""" )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys _snake_case : List[str] = [] _snake_case : List[str] = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): _snake_case : Any = flax_key_tuple[0] == pt_model.base_model_prefix _snake_case : Tuple = """.""".join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: _snake_case : List[Any] = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: _snake_case : str = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(snake_case__ ) not in pt_model_dict: # conv layer _snake_case : Dict = flax_key_tuple[:-1] + ("""weight""",) _snake_case : str = jnp.transpose(snake_case__ , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(snake_case__ ) not in pt_model_dict: # linear layer _snake_case : str = flax_key_tuple[:-1] + ("""weight""",) _snake_case : Union[str, Any] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: _snake_case : Tuple = flax_key_tuple[:-1] + ("""weight""",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: _snake_case : List[Any] = flax_key_tuple[:-1] + ("""running_mean""",) elif "var" in flax_key_tuple[-1]: _snake_case : List[str] = flax_key_tuple[:-1] + ("""running_var""",) if "batch_stats" in flax_state: _snake_case : int = """.""".join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: _snake_case : Union[str, Any] = """.""".join(snake_case__ ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. _snake_case : Optional[Any] = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: _snake_case : str = key.split(""".""" ) _snake_case : Optional[Any] = None if key_components[-3::2] == ["parametrizations", "original0"]: _snake_case : List[str] = key_components[-2] + """_g""" elif key_components[-3::2] == ["parametrizations", "original1"]: _snake_case : List[Any] = key_components[-2] + """_v""" if name is not None: _snake_case : int = key_components[:-3] + [name] _snake_case : Optional[int] = """.""".join(snake_case__ ) _snake_case : Any = key if flax_key in special_pt_names: _snake_case : Optional[int] = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " F"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." ) else: # add weight to pytorch dict _snake_case : str = np.asarray(snake_case__ ) if not isinstance(snake_case__ , np.ndarray ) else flax_tensor _snake_case : int = torch.from_numpy(snake_case__ ) # remove from missing keys missing_keys.remove(snake_case__ ) else: # weight is not expected by PyTorch model unexpected_keys.append(snake_case__ ) pt_model.load_state_dict(snake_case__ ) # re-transform missing_keys to list _snake_case : int = list(snake_case__ ) if len(snake_case__ ) > 0: logger.warning( """Some weights of the Flax model were not used when initializing the PyTorch model""" F" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" F" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" """ (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This""" F" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" """ to be exactly identical (e.g. initializing a BertForSequenceClassification model from a""" """ FlaxBertForSequenceClassification model).""" ) else: logger.warning(F"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n" ) if len(snake_case__ ) > 0: logger.warning( F"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" F" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" """ use it for predictions and inference.""" ) else: logger.warning( F"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n" """If your task is similar to the task the model of the checkpoint was trained on, """ F"you can already use {pt_model.__class__.__name__} for predictions without further training." ) return pt_model
64
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def UpperCAmelCase__ (snake_case__ : Optional[int] , snake_case__ : Any=7 ): """simple docstring""" _snake_case : Any = None if token is not None: _snake_case : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} # The id of a workflow (not of a workflow run) _snake_case : List[str] = """636036""" _snake_case : Union[str, Any] = F"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}" _snake_case : str = requests.get(snake_case__ , headers=snake_case__ ).json() return result["workflow_runs"] def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : str = get_daily_ci_runs(snake_case__ ) _snake_case : str = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _snake_case : List[str] = workflow_run["""id"""] break return workflow_run_id def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Union[str, Any] , snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[Any] = get_last_daily_ci_runs(snake_case__ ) if workflow_run_id is not None: _snake_case : Optional[Any] = get_artifacts_links(worflow_run_id=snake_case__ , token=snake_case__ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _snake_case : Optional[int] = artifacts_links[artifact_name] download_artifact( artifact_name=snake_case__ , artifact_url=snake_case__ , output_dir=snake_case__ , token=snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] , snake_case__ : List[str] , snake_case__ : int ): """simple docstring""" get_last_daily_ci_artifacts(snake_case__ , snake_case__ , snake_case__ ) _snake_case : int = {} for artifact_name in artifact_names: _snake_case : int = os.path.join(snake_case__ , F"{artifact_name}.zip" ) if os.path.isfile(snake_case__ ): _snake_case : Tuple = {} with zipfile.ZipFile(snake_case__ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case__ ): # read the file with z.open(snake_case__ ) as f: _snake_case : Any = f.read().decode("""UTF-8""" ) return results
64
1
"""simple docstring""" import requests A_ = '''YOUR API KEY''' def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str = giphy_api_key ): """simple docstring""" _snake_case : List[Any] = """+""".join(query.split() ) _snake_case : Optional[int] = F"https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}" _snake_case : int = requests.get(snake_case__ ).json()["""data"""] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('''\n'''.join(get_gifs('''space ship''')))
64
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging A_ = logging.get_logger(__name__) class lowercase: '''simple docstring''' lowercase__ = 42 lowercase__ = None @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Tuple, a_: int, a_: int, a_: str, **a_: Dict ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any], a_: List[str] ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.is_available(): raise RuntimeError( f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}." ) @classmethod def UpperCamelCase_ ( cls: Tuple ): '''simple docstring''' return f"`pip install {cls.pip_package or cls.name}`" class lowercase( __a ): '''simple docstring''' lowercase__ = "optuna" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def UpperCamelCase_ ( self: Union[str, Any], a_: List[Any], a_: int, a_: str, **a_: List[str] ): '''simple docstring''' return run_hp_search_optuna(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], a_: Any ): '''simple docstring''' return default_hp_space_optuna(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "ray" lowercase__ = "'ray[tune]'" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_ray_available() def UpperCamelCase_ ( self: int, a_: Optional[Any], a_: int, a_: str, **a_: List[Any] ): '''simple docstring''' return run_hp_search_ray(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Tuple ): '''simple docstring''' return default_hp_space_ray(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "sigopt" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def UpperCamelCase_ ( self: Dict, a_: str, a_: int, a_: str, **a_: int ): '''simple docstring''' return run_hp_search_sigopt(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: List[str] ): '''simple docstring''' return default_hp_space_sigopt(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "wandb" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def UpperCamelCase_ ( self: Optional[Any], a_: str, a_: int, a_: str, **a_: Union[str, Any] ): '''simple docstring''' return run_hp_search_wandb(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Any ): '''simple docstring''' return default_hp_space_wandb(a_ ) A_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def UpperCAmelCase__ (): """simple docstring""" _snake_case : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(snake_case__ ) > 0: _snake_case : Any = available_backends[0].name if len(snake_case__ ) > 1: logger.info( F"{len(snake_case__ )} hyperparameter search backends available. Using {name} as the default." ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( F" - To install {backend.name} run {backend.pip_install()}" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
64
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } A_ = { '''yjernite/retribert-base-uncased''': 5_12, } A_ = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = RetriBertTokenizer lowercase__ = ["input_ids", "attention_mask"] def __init__( self: int, a_: int=None, a_: Dict=None, a_: Any=True, a_: int="[UNK]", a_: Any="[SEP]", a_: List[Any]="[PAD]", a_: List[Any]="[CLS]", a_: str="[MASK]", a_: Dict=True, a_: Optional[int]=None, **a_: Tuple, ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Dict = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : List[Any] = do_lower_case _snake_case : List[str] = strip_accents _snake_case : Tuple = tokenize_chinese_chars _snake_case : Tuple = normalizer_class(**a_ ) _snake_case : List[str] = do_lower_case def UpperCamelCase_ ( self: Any, a_: str, a_: Optional[int]=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: List[str], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: Dict, a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : Union[str, Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowercase( __a ): '''simple docstring''' lowercase__ = ["image_processor", "tokenizer"] lowercase__ = "AutoImageProcessor" lowercase__ = "AutoTokenizer" def __init__( self: List[str], a_: List[str]=None, a_: Tuple=None, **a_: Tuple ): '''simple docstring''' _snake_case : str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""", a_, ) _snake_case : str = kwargs.pop("""feature_extractor""" ) _snake_case : Union[str, Any] = 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__(a_, a_ ) _snake_case : Dict = self.image_processor _snake_case : Any = False def __call__( self: Any, *a_: Any, **a_: Tuple ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*a_, **a_ ) _snake_case : Dict = kwargs.pop("""images""", a_ ) _snake_case : Optional[Any] = kwargs.pop("""text""", a_ ) if len(a_ ) > 0: _snake_case : Optional[int] = args[0] _snake_case : Tuple = args[1:] if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: _snake_case : Tuple = self.image_processor(a_, *a_, **a_ ) if text is not None: _snake_case : Tuple = self.tokenizer(a_, **a_ ) if text is None: return inputs elif images is None: return encodings else: _snake_case : List[str] = encodings["""input_ids"""] return inputs def UpperCamelCase_ ( self: Optional[int], *a_: Tuple, **a_: List[str] ): '''simple docstring''' return self.tokenizer.batch_decode(*a_, **a_ ) def UpperCamelCase_ ( self: int, *a_: List[str], **a_: int ): '''simple docstring''' return self.tokenizer.decode(*a_, **a_ ) @contextmanager def UpperCamelCase_ ( self: Dict ): '''simple docstring''' warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your images inputs, or in a separate call.""" ) _snake_case : Any = True _snake_case : Optional[int] = self.tokenizer yield _snake_case : int = self.image_processor _snake_case : Optional[int] = False def UpperCamelCase_ ( self: Dict, a_: Optional[Any], a_: str=False, a_: Optional[Any]=None ): '''simple docstring''' if added_vocab is None: _snake_case : Dict = self.tokenizer.get_added_vocab() _snake_case : str = {} while tokens: _snake_case : Union[str, Any] = re.search(r"""<s_(.*?)>""", a_, re.IGNORECASE ) if start_token is None: break _snake_case : List[Any] = start_token.group(1 ) _snake_case : str = re.search(rf"</s_{key}>", a_, re.IGNORECASE ) _snake_case : Dict = start_token.group() if end_token is None: _snake_case : List[Any] = tokens.replace(a_, """""" ) else: _snake_case : List[str] = end_token.group() _snake_case : str = re.escape(a_ ) _snake_case : str = re.escape(a_ ) _snake_case : Union[str, Any] = re.search(f"{start_token_escaped}(.*?){end_token_escaped}", a_, re.IGNORECASE ) if content is not None: _snake_case : int = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node _snake_case : List[Any] = self.tokenajson(a_, is_inner_value=a_, added_vocab=a_ ) if value: if len(a_ ) == 1: _snake_case : List[str] = value[0] _snake_case : List[str] = value else: # leaf nodes _snake_case : Tuple = [] for leaf in content.split(r"""<sep/>""" ): _snake_case : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": _snake_case : int = leaf[1:-2] # for categorical special tokens output[key].append(a_ ) if len(output[key] ) == 1: _snake_case : int = output[key][0] _snake_case : Any = tokens[tokens.find(a_ ) + len(a_ ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=a_, added_vocab=a_ ) if len(a_ ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""", a_, ) return self.image_processor_class @property def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""", a_, ) return self.image_processor
64
1
"""simple docstring""" import socket def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) _snake_case : int = socket.gethostname() _snake_case : Any = 1_23_12 sock.connect((host, port) ) sock.send(B"""Hello server!""" ) with open("""Received_file""" , """wb""" ) as out_file: print("""File opened""" ) print("""Receiving data...""" ) while True: _snake_case : Dict = sock.recv(10_24 ) if not data: break out_file.write(snake_case__ ) print("""Successfully received the file""" ) sock.close() print("""Connection closed""" ) if __name__ == "__main__": main()
64
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : int = 0.00 _snake_case : int = 0 for resistor in resistors: if resistor <= 0: _snake_case : Dict = F"Resistor at index {index} has a negative or zero value!" raise ValueError(snake_case__ ) first_sum += 1 / float(snake_case__ ) index += 1 return 1 / first_sum def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : Union[str, Any] = 0.00 _snake_case : Any = 0 for resistor in resistors: sum_r += resistor if resistor < 0: _snake_case : Any = F"Resistor at index {index} has a negative value!" raise ValueError(snake_case__ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
64
1
"""simple docstring""" import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: Optional[Any], a_: List[Any]=13, a_: List[Any]=7, a_: Tuple=False, a_: str=True, a_: str=False, a_: List[str]=True, a_: Dict=33, a_: Any=32, a_: Tuple=5, a_: List[Any]=4, a_: Any=37, a_: str="gelu", a_: Tuple=0.1, a_: Union[str, Any]=0.1, a_: Dict=512, a_: str=16, a_: str=2, a_: Tuple=0.02, a_: Optional[int]=3, a_: str=4, a_: Any=None, ): '''simple docstring''' _snake_case : Optional[Any] = parent _snake_case : Optional[Any] = batch_size _snake_case : int = seq_length _snake_case : Optional[int] = is_training _snake_case : List[str] = use_input_mask _snake_case : List[Any] = use_token_type_ids _snake_case : Any = use_labels _snake_case : List[Any] = vocab_size _snake_case : Any = hidden_size _snake_case : int = num_hidden_layers _snake_case : str = num_attention_heads _snake_case : Optional[int] = intermediate_size _snake_case : Union[str, Any] = hidden_act _snake_case : Tuple = hidden_dropout_prob _snake_case : Union[str, Any] = attention_probs_dropout_prob _snake_case : Optional[Any] = max_position_embeddings _snake_case : Union[str, Any] = type_vocab_size _snake_case : Any = type_sequence_label_size _snake_case : str = initializer_range _snake_case : Tuple = num_labels _snake_case : Any = num_choices _snake_case : Optional[int] = scope def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Dict = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) _snake_case : Any = None if self.use_input_mask: _snake_case : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case : List[Any] = None _snake_case : Any = None _snake_case : Optional[int] = None if self.use_labels: _snake_case : Optional[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size ) _snake_case : List[Any] = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) _snake_case : Tuple = ids_tensor([self.batch_size], self.num_choices ) _snake_case : Any = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, pad_token_id=1, 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, ) def UpperCamelCase_ ( self: int, a_: Union[str, Any], a_: Dict, a_: List[str], a_: Any, a_: Any, a_: Any ): '''simple docstring''' _snake_case : Dict = EsmModel(config=a_ ) model.to(a_ ) model.eval() _snake_case : List[str] = model(a_, attention_mask=a_ ) _snake_case : Any = model(a_ ) _snake_case : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size) ) def UpperCamelCase_ ( self: Tuple, a_: int, a_: Dict, a_: Optional[Any], a_: str, a_: Union[str, Any], a_: List[str] ): '''simple docstring''' _snake_case : Union[str, Any] = EsmForMaskedLM(config=a_ ) model.to(a_ ) model.eval() _snake_case : Optional[Any] = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self: List[Any], a_: Optional[Any], a_: Any, a_: Any, a_: str, a_: Union[str, Any], a_: Tuple ): '''simple docstring''' _snake_case : Optional[int] = self.num_labels _snake_case : Tuple = EsmForTokenClassification(config=a_ ) model.to(a_ ) model.eval() _snake_case : List[Any] = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' _snake_case : Union[str, Any] = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) : str = config_and_inputs _snake_case : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowercase( __a , __a , unittest.TestCase ): '''simple docstring''' lowercase__ = False lowercase__ = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) lowercase__ = () lowercase__ = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) lowercase__ = True def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : str = EsmModelTester(self ) _snake_case : Union[str, Any] = ConfigTester(self, config_class=a_, hidden_size=37 ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _snake_case : str = type self.model_tester.create_and_check_model(*a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a_ ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @slow def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : Tuple = EsmModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Any = self.model_tester.prepare_config_and_inputs()[0] _snake_case : Union[str, Any] = EsmEmbeddings(config=a_ ) _snake_case : Union[str, Any] = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) _snake_case : int = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _snake_case : List[Any] = create_position_ids_from_input_ids(a_, model.padding_idx ) self.assertEqual(position_ids.shape, expected_positions.shape ) self.assertTrue(torch.all(torch.eq(a_, a_ ) ) ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Any = self.model_tester.prepare_config_and_inputs()[0] _snake_case : Optional[int] = EsmEmbeddings(config=a_ ) _snake_case : int = torch.empty(2, 4, 30 ) _snake_case : Any = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _snake_case : int = torch.as_tensor([expected_single_positions, expected_single_positions] ) _snake_case : List[Any] = embeddings.create_position_ids_from_inputs_embeds(a_ ) self.assertEqual(position_ids.shape, expected_positions.shape ) self.assertTrue(torch.all(torch.eq(a_, a_ ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def UpperCamelCase_ ( self: int ): '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' pass @require_torch class lowercase( __a ): '''simple docstring''' @slow def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' with torch.no_grad(): _snake_case : Optional[Any] = EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _snake_case : Union[str, Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) _snake_case : Optional[int] = model(a_ )[0] _snake_case : Tuple = 33 _snake_case : str = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape, a_ ) _snake_case : str = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3], a_, atol=1E-4 ) ) @slow def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' with torch.no_grad(): _snake_case : Tuple = EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _snake_case : Any = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) _snake_case : Optional[int] = model(a_ )[0] # compare the actual values for a slice. _snake_case : Union[str, Any] = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3], a_, atol=1E-4 ) )
64
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''', }, '''merges_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''Salesforce/codegen-350M-mono''': ( '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json''' ), }, } A_ = { '''Salesforce/codegen-350M-mono''': 20_48, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] lowercase__ = CodeGenTokenizer def __init__( self: Union[str, Any], a_: List[Any]=None, a_: str=None, a_: str=None, a_: Dict="<|endoftext|>", a_: Tuple="<|endoftext|>", a_: str="<|endoftext|>", a_: List[Any]=False, **a_: List[str], ): '''simple docstring''' super().__init__( a_, a_, tokenizer_file=a_, unk_token=a_, bos_token=a_, eos_token=a_, add_prefix_space=a_, **a_, ) if kwargs.pop("""add_bos_token""", a_ ): _snake_case : str = kwargs.pop("""name_or_path""", """""" ) raise ValueError( """Currenty GPT2's fast tokenizer does NOT support adding a BOS token.""" """Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n""" f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n" f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n" """This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.""" """ so that the fast tokenizer works correctly.""" ) _snake_case : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : Dict = getattr(a_, pre_tok_state.pop("""type""" ) ) _snake_case : Dict = add_prefix_space _snake_case : str = pre_tok_class(**a_ ) _snake_case : List[Any] = add_prefix_space def UpperCamelCase_ ( self: Any, *a_: Any, **a_: int ): '''simple docstring''' _snake_case : Optional[int] = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], *a_: Any, **a_: List[str] ): '''simple docstring''' _snake_case : Dict = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : List[Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ ) def UpperCamelCase_ ( self: str, a_: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], a_: bool = False, a_: bool = None, a_: Optional[List[str]] = None, **a_: List[str], ): '''simple docstring''' _snake_case : Any = super().decode( token_ids=a_, skip_special_tokens=a_, clean_up_tokenization_spaces=a_, **a_, ) if truncate_before_pattern is not None and len(a_ ) > 0: _snake_case : List[str] = self.truncate(a_, a_ ) return decoded_text def UpperCamelCase_ ( self: Dict, a_: Tuple, a_: Optional[Any] ): '''simple docstring''' def find_re(a_: Dict, a_: str, a_: Union[str, Any] ): _snake_case : Any = pattern.search(a_, a_ ) return m.start() if m else -1 _snake_case : Tuple = [re.compile(a_, re.MULTILINE ) for pattern in truncate_before_pattern] _snake_case : List[Any] = list(re.finditer("""^print""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : int = completion[: prints[1].start()] _snake_case : List[str] = list(re.finditer("""^def""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : List[Any] = completion[: defs[1].start()] _snake_case : int = 0 _snake_case : List[Any] = [ pos for pos in [find_re(a_, a_, a_ ) for terminal in terminals] if pos != -1 ] if len(a_ ) > 0: return completion[: min(a_ )] else: return completion
64
1
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = RoCBertTokenizer lowercase__ = None lowercase__ = False lowercase__ = True lowercase__ = filter_non_english def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' super().setUp() _snake_case : List[str] = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] _snake_case : Tuple = {} _snake_case : Any = {} for i, value in enumerate(a_ ): _snake_case : List[str] = i _snake_case : Optional[int] = i _snake_case : List[Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) _snake_case : Dict = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""word_shape_file"""] ) _snake_case : Optional[Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file, """w""", encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file, """w""", encoding="""utf-8""" ) as word_shape_writer: json.dump(a_, a_, ensure_ascii=a_ ) with open(self.word_pronunciation_file, """w""", encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(a_, a_, ensure_ascii=a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Optional[int] = self.tokenizer_class(self.vocab_file, self.word_shape_file, self.word_pronunciation_file ) _snake_case : str = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(a_, ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ), [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(a_ ), [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(a_ ), [5, 6, 2, 5, 7, 8] ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ), ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Tuple = RoCBertBasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ), ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ), ["""hello"""] ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = RoCBertBasicTokenizer(do_lower_case=a_, strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ), ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ), ["""h\u00E9llo"""] ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Any = RoCBertBasicTokenizer(do_lower_case=a_, strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ), ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ), ["""hello"""] ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ), ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ), ["""hello"""] ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Optional[int] = RoCBertBasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ), ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : str = RoCBertBasicTokenizer(do_lower_case=a_, strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ), ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=a_, strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ), ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : str = RoCBertBasicTokenizer(do_lower_case=a_, never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ), ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Optional[Any] = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] _snake_case : Optional[Any] = {} for i, token in enumerate(a_ ): _snake_case : Dict = i _snake_case : Optional[Any] = RoCBertWordpieceTokenizer(vocab=a_, unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ), [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ), ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ), ["""[UNK]""", """runn""", """##ing"""] ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Optional[int] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(a_ ) for t in ["""Test""", """\xad""", """test"""]], [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: _snake_case : Optional[int] = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(a_ ) for t in ["""Test""", """\xad""", """test"""]], [["""[UNK]"""], [], ["""[UNK]"""]] ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : Optional[int] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) _snake_case : List[Any] = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." _snake_case : List[Any] = tokenizer_r.encode_plus( a_, return_attention_mask=a_, return_token_type_ids=a_, return_offsets_mapping=a_, add_special_tokens=a_, ) _snake_case : Optional[Any] = tokenizer_r.do_lower_case if hasattr(a_, """do_lower_case""" ) else False _snake_case : Optional[Any] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results], tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results], tokens["""offset_mapping"""] ) def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = ["""的""", """人""", """有"""] _snake_case : Any = """""".join(a_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : int = True _snake_case : Tuple = self.tokenizer_class.from_pretrained(a_, **a_ ) _snake_case : List[Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) _snake_case : Optional[Any] = tokenizer_p.encode(a_, add_special_tokens=a_ ) _snake_case : int = tokenizer_r.encode(a_, add_special_tokens=a_ ) _snake_case : Optional[Any] = tokenizer_r.convert_ids_to_tokens(a_ ) _snake_case : Optional[int] = tokenizer_p.convert_ids_to_tokens(a_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(a_, a_ ) self.assertListEqual(a_, a_ ) _snake_case : List[str] = False _snake_case : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) _snake_case : str = self.tokenizer_class.from_pretrained(a_, **a_ ) _snake_case : Optional[Any] = tokenizer_r.encode(a_, add_special_tokens=a_ ) _snake_case : Any = tokenizer_p.encode(a_, add_special_tokens=a_ ) _snake_case : Optional[int] = tokenizer_r.convert_ids_to_tokens(a_ ) _snake_case : Tuple = tokenizer_p.convert_ids_to_tokens(a_ ) # it is expected that only the first Chinese character is not preceded by "##". _snake_case : List[Any] = [ f"##{token}" if idx != 0 else token for idx, token in enumerate(a_ ) ] self.assertListEqual(a_, a_ ) self.assertListEqual(a_, a_ ) @slow def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Union[str, Any] = self.tokenizer_class(self.vocab_file, self.word_shape_file, self.word_pronunciation_file ) _snake_case : Tuple = tokenizer.encode("""你好""", add_special_tokens=a_ ) _snake_case : Optional[int] = tokenizer.encode("""你是谁""", add_special_tokens=a_ ) _snake_case : str = tokenizer.build_inputs_with_special_tokens(a_ ) _snake_case : int = tokenizer.build_inputs_with_special_tokens(a_, a_ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : List[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): _snake_case : int = """你好,你是谁""" _snake_case : List[str] = tokenizer.tokenize(a_ ) _snake_case : List[str] = tokenizer.convert_tokens_to_ids(a_ ) _snake_case : List[Any] = tokenizer.convert_tokens_to_shape_ids(a_ ) _snake_case : Optional[Any] = tokenizer.convert_tokens_to_pronunciation_ids(a_ ) _snake_case : Dict = tokenizer.prepare_for_model( a_, a_, a_, add_special_tokens=a_ ) _snake_case : Dict = tokenizer.encode_plus(a_, add_special_tokens=a_ ) self.assertEqual(a_, a_ )
64
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : List[Any] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _snake_case : Tuple = 1_92 _snake_case : Any = 7_68 _snake_case : Any = 12 _snake_case : List[Any] = 3 _snake_case : int = [8_00, 13_33] _snake_case : Tuple = False elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = 3_30 _snake_case : List[str] = 14 _snake_case : List[str] = 6 _snake_case : Union[str, Any] = 13_20 elif "yolos_s" in yolos_name: _snake_case : Union[str, Any] = 3_84 _snake_case : List[str] = 15_36 _snake_case : Any = 12 _snake_case : Optional[int] = 6 elif "yolos_b" in yolos_name: _snake_case : Dict = [8_00, 13_44] _snake_case : str = 91 _snake_case : Optional[Any] = """huggingface/label-files""" _snake_case : str = """coco-detection-id2label.json""" _snake_case : str = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="""dataset""" ) , """r""" ) ) _snake_case : Union[str, Any] = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[str] = idalabel _snake_case : List[str] = {v: k for k, v in idalabel.items()} return config def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosConfig , snake_case__ : bool = False ): """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : int = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) _snake_case : Union[str, Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Any = in_proj_weight[: config.hidden_size, :] _snake_case : Optional[Any] = in_proj_bias[: config.hidden_size] _snake_case : Optional[int] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Tuple = in_proj_weight[-config.hidden_size :, :] _snake_case : List[Any] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" if "backbone" in name: _snake_case : str = name.replace("""backbone""" , """vit""" ) if "cls_token" in name: _snake_case : Union[str, Any] = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "det_token" in name: _snake_case : str = name.replace("""det_token""" , """embeddings.detection_tokens""" ) if "mid_pos_embed" in name: _snake_case : str = name.replace("""mid_pos_embed""" , """encoder.mid_position_embeddings""" ) if "pos_embed" in name: _snake_case : Tuple = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: _snake_case : str = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "blocks" in name: _snake_case : str = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: _snake_case : Any = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: _snake_case : str = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: _snake_case : List[str] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: _snake_case : str = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: _snake_case : List[str] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: _snake_case : int = name.replace("""mlp.fc2""" , """output.dense""" ) if "class_embed" in name: _snake_case : Union[str, Any] = name.replace("""class_embed""" , """class_labels_classifier""" ) if "bbox_embed" in name: _snake_case : str = name.replace("""bbox_embed""" , """bbox_predictor""" ) if "vit.norm" in name: _snake_case : Union[str, Any] = name.replace("""vit.norm""" , """vit.layernorm""" ) return name def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosForObjectDetection ): """simple docstring""" for key in orig_state_dict.copy().keys(): _snake_case : List[str] = orig_state_dict.pop(snake_case__ ) if "qkv" in key: _snake_case : Optional[Any] = key.split(""".""" ) _snake_case : Optional[Any] = int(key_split[2] ) _snake_case : Optional[int] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _snake_case : str = val[:dim, :] _snake_case : Optional[Any] = val[ dim : dim * 2, : ] _snake_case : Optional[Any] = val[-dim:, :] else: _snake_case : Dict = val[:dim] _snake_case : Any = val[dim : dim * 2] _snake_case : Dict = val[-dim:] else: _snake_case : Tuple = val return orig_state_dict def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Union[str, Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : str , snake_case__ : bool = False ): """simple docstring""" _snake_case : Optional[Any] = get_yolos_config(snake_case__ ) # load original state_dict _snake_case : Optional[int] = torch.load(snake_case__ , map_location="""cpu""" )["""model"""] # load 🤗 model _snake_case : Optional[Any] = YolosForObjectDetection(snake_case__ ) model.eval() _snake_case : Optional[Any] = convert_state_dict(snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ ) # Check outputs on an image, prepared by YolosImageProcessor _snake_case : List[str] = 8_00 if yolos_name != """yolos_ti""" else 5_12 _snake_case : Optional[int] = YolosImageProcessor(format="""coco_detection""" , size=snake_case__ ) _snake_case : Optional[Any] = image_processor(images=prepare_img() , return_tensors="""pt""" ) _snake_case : Optional[Any] = model(**snake_case__ ) _snake_case , _snake_case : Optional[int] = outputs.logits, outputs.pred_boxes _snake_case , _snake_case : Dict = None, None if yolos_name == "yolos_ti": _snake_case : Optional[Any] = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) _snake_case : Tuple = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": _snake_case : List[str] = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) _snake_case : List[str] = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": _snake_case : Dict = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) _snake_case : Union[str, Any] = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) _snake_case : Optional[Any] = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": _snake_case : int = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) _snake_case : Optional[int] = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(F"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , snake_case__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , snake_case__ , atol=1e-4 ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if push_to_hub: _snake_case : Dict = { """yolos_ti""": """yolos-tiny""", """yolos_s_200_pre""": """yolos-small""", """yolos_s_300_pre""": """yolos-small-300""", """yolos_s_dWr""": """yolos-small-dwr""", """yolos_base""": """yolos-base""", } print("""Pushing to the hub...""" ) _snake_case : str = model_mapping[yolos_name] image_processor.push_to_hub(snake_case__ , organization="""hustvl""" ) model.push_to_hub(snake_case__ , organization="""hustvl""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.pth file).''' ) 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.''' ) A_ = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
64
1
"""simple docstring""" 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 A_ = logging.get_logger(__name__) A_ = { '''microsoft/beit-base-patch16-224-pt22k''': ( '''https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json''' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class lowercase( __a ): '''simple docstring''' lowercase__ = "beit" def __init__( self: int, a_: int=8_192, a_: Any=768, a_: Optional[int]=12, a_: Dict=12, a_: Dict=3_072, a_: int="gelu", a_: List[Any]=0.0, a_: List[Any]=0.0, a_: int=0.02, a_: List[Any]=1E-12, a_: Tuple=224, a_: Union[str, Any]=16, a_: str=3, a_: Dict=False, a_: Optional[int]=False, a_: Optional[int]=False, a_: Union[str, Any]=False, a_: List[Any]=0.1, a_: int=0.1, a_: Optional[Any]=True, a_: Any=[3, 5, 7, 11], a_: Tuple=[1, 2, 3, 6], a_: Union[str, Any]=True, a_: Union[str, Any]=0.4, a_: Any=256, a_: Optional[int]=1, a_: Tuple=False, a_: Dict=255, **a_: Optional[int], ): '''simple docstring''' super().__init__(**a_ ) _snake_case : List[str] = vocab_size _snake_case : Optional[int] = hidden_size _snake_case : Union[str, Any] = num_hidden_layers _snake_case : int = num_attention_heads _snake_case : Optional[Any] = intermediate_size _snake_case : Union[str, Any] = hidden_act _snake_case : List[str] = hidden_dropout_prob _snake_case : Tuple = attention_probs_dropout_prob _snake_case : Optional[int] = initializer_range _snake_case : Union[str, Any] = layer_norm_eps _snake_case : str = image_size _snake_case : Dict = patch_size _snake_case : Tuple = num_channels _snake_case : List[str] = use_mask_token _snake_case : Any = use_absolute_position_embeddings _snake_case : Optional[Any] = use_relative_position_bias _snake_case : Any = use_shared_relative_position_bias _snake_case : Optional[Any] = layer_scale_init_value _snake_case : Dict = drop_path_rate _snake_case : str = use_mean_pooling # decode head attributes (semantic segmentation) _snake_case : List[str] = out_indices _snake_case : Union[str, Any] = pool_scales # auxiliary head attributes (semantic segmentation) _snake_case : List[str] = use_auxiliary_head _snake_case : int = auxiliary_loss_weight _snake_case : List[str] = auxiliary_channels _snake_case : Union[str, Any] = auxiliary_num_convs _snake_case : List[Any] = auxiliary_concat_input _snake_case : List[str] = semantic_loss_ignore_index class lowercase( __a ): '''simple docstring''' lowercase__ = version.parse("1.11" ) @property def UpperCamelCase_ ( self: str ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' return 1E-4
64
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str]=False ): """simple docstring""" _snake_case : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"module.blocks.{i}.norm1.weight", F"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((F"module.blocks.{i}.norm1.bias", F"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (F"module.blocks.{i}.attn.proj.weight", F"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.attn.proj.bias", F"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((F"module.blocks.{i}.norm2.weight", F"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((F"module.blocks.{i}.norm2.bias", F"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.weight", F"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.bias", F"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.weight", F"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.bias", F"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _snake_case : Any = [(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 UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : Dict , snake_case__ : List[str]=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _snake_case : List[Any] = """""" else: _snake_case : List[Any] = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.weight" ) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Optional[Any] = in_proj_weight[ : config.hidden_size, : ] _snake_case : Union[str, Any] = in_proj_bias[: config.hidden_size] _snake_case : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] _snake_case : List[str] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Tuple = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" _snake_case : List[str] = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : int ): """simple docstring""" _snake_case : Optional[Any] = dct.pop(snake_case__ ) _snake_case : Union[str, Any] = val def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : str ): """simple docstring""" _snake_case : str = ViTMSNConfig() _snake_case : Any = 10_00 _snake_case : Tuple = """datasets/huggingface/label-files""" _snake_case : Dict = """imagenet-1k-id2label.json""" _snake_case : int = json.load(open(hf_hub_download(snake_case__ , snake_case__ ) , """r""" ) ) _snake_case : Any = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[Any] = idalabel _snake_case : str = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: _snake_case : Tuple = 3_84 _snake_case : Dict = 15_36 _snake_case : Tuple = 6 elif "l16" in checkpoint_url: _snake_case : Any = 10_24 _snake_case : int = 40_96 _snake_case : str = 24 _snake_case : Optional[int] = 16 _snake_case : List[Any] = 0.1 elif "b4" in checkpoint_url: _snake_case : Tuple = 4 elif "l7" in checkpoint_url: _snake_case : int = 7 _snake_case : Dict = 10_24 _snake_case : Optional[Any] = 40_96 _snake_case : Any = 24 _snake_case : Union[str, Any] = 16 _snake_case : Optional[int] = 0.1 _snake_case : int = ViTMSNModel(snake_case__ ) _snake_case : Optional[int] = torch.hub.load_state_dict_from_url(snake_case__ , map_location="""cpu""" )["""target_encoder"""] _snake_case : List[str] = ViTImageProcessor(size=config.image_size ) remove_projection_head(snake_case__ ) _snake_case : List[str] = create_rename_keys(snake_case__ , base_model=snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_q_k_v(snake_case__ , snake_case__ , base_model=snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() _snake_case : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) _snake_case : str = ViTImageProcessor( size=config.image_size , image_mean=snake_case__ , image_std=snake_case__ ) _snake_case : Any = image_processor(images=snake_case__ , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) _snake_case : int = model(**snake_case__ ) _snake_case : List[Any] = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: _snake_case : Optional[Any] = torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] ) elif "b16" in checkpoint_url: _snake_case : str = torch.tensor([[14.28_89, -18.90_45, 11.72_81]] ) elif "l16" in checkpoint_url: _snake_case : Optional[int] = torch.tensor([[41.50_28, -22.86_81, 45.64_75]] ) elif "b4" in checkpoint_url: _snake_case : List[Any] = torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] ) else: _snake_case : Optional[int] = torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , snake_case__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A_ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
64
1
"""simple docstring""" import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : Any , snake_case__ : Any ): """simple docstring""" _snake_case : Optional[Any] = TaConfig.from_json_file(snake_case__ ) print(F"Building PyTorch model from configuration: {config}" ) _snake_case : Optional[Any] = TaForConditionalGeneration(snake_case__ ) # Load weights from tf checkpoint load_tf_weights_in_ta(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) A_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
64
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str ): """simple docstring""" _snake_case : Optional[Any] = list(snake_case__ ) _snake_case : List[Any] = list(snake_case__ ) _snake_case : List[Any] = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count += 1 _snake_case : Any = """_""" if count > 1: return False else: return "".join(snake_case__ ) def UpperCAmelCase__ (snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [] while True: _snake_case : Union[str, Any] = ["""$"""] * len(snake_case__ ) _snake_case : int = [] for i in range(len(snake_case__ ) ): for j in range(i + 1 , len(snake_case__ ) ): _snake_case : List[Any] = compare_string(binary[i] , binary[j] ) if k is False: _snake_case : Dict = """*""" _snake_case : List[Any] = """*""" temp.append("""X""" ) for i in range(len(snake_case__ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case__ ) == 0: return pi _snake_case : Optional[int] = list(set(snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Sequence[float] ): """simple docstring""" _snake_case : Optional[int] = [] for minterm in minterms: _snake_case : Any = """""" for _ in range(snake_case__ ): _snake_case : Optional[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case__ ) return temp def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : int ): """simple docstring""" _snake_case : Dict = list(snake_case__ ) _snake_case : List[str] = list(snake_case__ ) _snake_case : Tuple = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCAmelCase__ (snake_case__ : list[list[int]] , snake_case__ : list[str] ): """simple docstring""" _snake_case : Any = [] _snake_case : Union[str, Any] = [0] * len(snake_case__ ) for i in range(len(chart[0] ) ): _snake_case : Tuple = 0 _snake_case : str = -1 for j in range(len(snake_case__ ) ): if chart[j][i] == 1: count += 1 _snake_case : Union[str, Any] = j if count == 1: _snake_case : Union[str, Any] = 1 for i in range(len(snake_case__ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case__ ) ): _snake_case : List[Any] = 0 temp.append(prime_implicants[i] ) while True: _snake_case : Optional[int] = 0 _snake_case : str = -1 _snake_case : Any = 0 for i in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _snake_case : Dict = count_n _snake_case : Dict = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case__ ) ): _snake_case : Optional[Any] = 0 def UpperCAmelCase__ (snake_case__ : list[str] , snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [[0 for x in range(len(snake_case__ ) )] for x in range(len(snake_case__ ) )] for i in range(len(snake_case__ ) ): _snake_case : Any = prime_implicants[i].count("""_""" ) for j in range(len(snake_case__ ) ): if is_for_table(prime_implicants[i] , binary[j] , snake_case__ ): _snake_case : Tuple = 1 return chart def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = int(input("""Enter the no. of variables\n""" ) ) _snake_case : List[str] = [ float(snake_case__ ) for x in input( """Enter the decimal representation of Minterms 'Spaces Separated'\n""" ).split() ] _snake_case : List[str] = decimal_to_binary(snake_case__ , snake_case__ ) _snake_case : str = check(snake_case__ ) print("""Prime Implicants are:""" ) print(snake_case__ ) _snake_case : int = prime_implicant_chart(snake_case__ , snake_case__ ) _snake_case : str = selection(snake_case__ , snake_case__ ) print("""Essential Prime Implicants are:""" ) print(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
64
1
"""simple docstring""" # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES A_ = '''tiny-wmt19-en-ru''' # Build # borrowed from a test A_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] A_ = dict(zip(vocab, range(len(vocab)))) A_ = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] with tempfile.TemporaryDirectory() as tmpdirname: A_ = Path(tmpdirname) A_ = build_dir / VOCAB_FILES_NAMES['''src_vocab_file'''] A_ = build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file'''] A_ = build_dir / VOCAB_FILES_NAMES['''merges_file'''] with open(src_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, '''w''') as fp: fp.write('''\n'''.join(merges)) A_ = FSMTTokenizer( langs=['''en''', '''ru'''], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) A_ = FSMTConfig( langs=['''ru''', '''en'''], src_vocab_size=10_00, tgt_vocab_size=10_00, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) A_ = FSMTForConditionalGeneration(config) print(F'''num of params {tiny_model.num_parameters()}''') # Test A_ = tokenizer(['''Making tiny model'''], return_tensors='''pt''') A_ = tiny_model(**batch) print('''test output:''', len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F'''Generated {mname_tiny}''') # Upload # transformers-cli upload tiny-wmt19-en-ru
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" stooge(snake_case__ , 0 , len(snake_case__ ) - 1 ) return arr def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int ): """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _snake_case , _snake_case : Tuple = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _snake_case : Dict = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case__ , i + t , (snake_case__) ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(stooge_sort(unsorted))
64
1
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def UpperCAmelCase__ (): """simple docstring""" _snake_case : Union[str, Any] = ArgumentParser( description=( """PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes""" ) ) # Optional arguments for the launch helper parser.add_argument("""--num_cores""" , type=snake_case__ , default=1 , help="""Number of TPU cores to use (1 or 8).""" ) # positional parser.add_argument( """training_script""" , type=snake_case__ , help=( """The full path to the single TPU training """ """program/script to be launched in parallel, """ """followed by all the arguments for the """ """training script""" ) , ) # rest from the training program parser.add_argument("""training_script_args""" , nargs=snake_case__ ) return parser.parse_args() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Union[str, Any] = parse_args() # Import training_script as a module. _snake_case : Dict = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _snake_case : int = script_fpath.stem _snake_case : int = importlib.import_module(snake_case__ ) # Patch sys.argv _snake_case : List[str] = [args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
64
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase( metaclass=__a ): '''simple docstring''' lowercase__ = ["note_seq"] def __init__( self: Dict, *a_: Union[str, Any], **a_: List[str] ): '''simple docstring''' requires_backends(self, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Optional[int], *a_: Any, **a_: Optional[Any] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Tuple, *a_: Optional[Any], **a_: List[str] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] )
64
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: A_ = None A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/spiece.model''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json''', }, } A_ = { '''google/fnet-base''': 5_12, '''google/fnet-large''': 5_12, } A_ = '''▁''' class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "token_type_ids"] lowercase__ = FNetTokenizer def __init__( self: List[str], a_: str=None, a_: Optional[Any]=None, a_: Tuple=False, a_: Any=True, a_: List[str]=True, a_: List[Any]="<unk>", a_: Optional[Any]="[SEP]", a_: Optional[int]="<pad>", a_: Optional[Any]="[CLS]", a_: int="[MASK]", **a_: Optional[Any], ): '''simple docstring''' _snake_case : str = ( AddedToken(a_, lstrip=a_, rstrip=a_, normalized=a_ ) if isinstance(a_, a_ ) else mask_token ) super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, remove_space=a_, keep_accents=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, **a_, ) _snake_case : Union[str, Any] = do_lower_case _snake_case : Dict = remove_space _snake_case : int = keep_accents _snake_case : Dict = vocab_file _snake_case : str = False if not self.vocab_file else True def UpperCamelCase_ ( self: Optional[Any], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : List[Any] = [self.sep_token_id] _snake_case : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self: Union[str, Any], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Any = [self.sep_token_id] _snake_case : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: List[str], a_: str, a_: Optional[str] = None ): '''simple docstring''' if not os.path.isdir(a_ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _snake_case : List[Any] = os.path.join( a_, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file, a_ ) return (out_vocab_file,)
64
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : int = data _snake_case : Dict = [0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def UpperCamelCase_ ( a_: Optional[Any], a_: Dict ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xffffffff def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) _snake_case : Optional[int] = self.data + padding + struct.pack(""">Q""", 8 * len(self.data ) ) return padded_data def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def UpperCamelCase_ ( self: Optional[Any], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = list(struct.unpack(""">16L""", a_ ) ) + [0] * 64 for i in range(16, 80 ): _snake_case : List[Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = self.padding() _snake_case : str = self.split_blocks() for block in self.blocks: _snake_case : Any = self.expand_block(a_ ) _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = self.h for i in range(0, 80 ): if 0 <= i < 20: _snake_case : int = (b & c) | ((~b) & d) _snake_case : str = 0X5a827999 elif 20 <= i < 40: _snake_case : Optional[int] = b ^ c ^ d _snake_case : str = 0X6ed9eba1 elif 40 <= i < 60: _snake_case : List[Any] = (b & c) | (b & d) | (c & d) _snake_case : List[Any] = 0X8f1bbcdc elif 60 <= i < 80: _snake_case : List[Any] = b ^ c ^ d _snake_case : int = 0Xca62c1d6 _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = ( self.rotate(a_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(a_, 30 ), c, d, ) _snake_case : Union[str, Any] = ( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = B"""Test String""" assert SHAaHash(snake_case__ ).final_hash() == hashlib.shaa(snake_case__ ).hexdigest() # noqa: S324 def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _snake_case : Union[str, Any] = parser.parse_args() _snake_case : List[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _snake_case : str = f.read() else: _snake_case : int = bytes(snake_case__ , """utf-8""" ) print(SHAaHash(snake_case__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
64
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, 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_vision_available, logging if is_vision_available(): import PIL A_ = logging.get_logger(__name__) class lowercase( __a ): '''simple docstring''' lowercase__ = ["pixel_values"] def __init__( self: List[Any], a_: bool = True, a_: Dict[str, int] = None, a_: PILImageResampling = PIL.Image.BICUBIC, a_: bool = True, a_: Dict[str, int] = None, a_: Union[int, float] = 1 / 255, a_: bool = True, a_: bool = True, a_: Optional[Union[float, List[float]]] = None, a_: Optional[Union[float, List[float]]] = None, **a_: Union[str, Any], ): '''simple docstring''' super().__init__(**a_ ) _snake_case : int = size if size is not None else {"""height""": 256, """width""": 256} _snake_case : Optional[int] = get_size_dict(a_ ) _snake_case : Union[str, Any] = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} _snake_case : str = get_size_dict(a_, param_name="""crop_size""" ) _snake_case : int = do_resize _snake_case : Any = size _snake_case : List[str] = resample _snake_case : str = do_center_crop _snake_case : Optional[Any] = crop_size _snake_case : Dict = do_rescale _snake_case : Optional[int] = rescale_factor _snake_case : str = do_normalize _snake_case : Optional[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _snake_case : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase_ ( self: Optional[int], a_: np.ndarray, a_: Dict[str, int], a_: PILImageResampling = PIL.Image.BICUBIC, a_: Optional[Union[str, ChannelDimension]] = None, **a_: Optional[Any], ): '''simple docstring''' _snake_case : Union[str, Any] = get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}" ) return resize( a_, size=(size["""height"""], size["""width"""]), resample=a_, data_format=a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: np.ndarray, a_: Dict[str, int], a_: Optional[Union[str, ChannelDimension]] = None, **a_: int, ): '''simple docstring''' _snake_case : Dict = get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}" ) return center_crop(a_, size=(size["""height"""], size["""width"""]), data_format=a_, **a_ ) def UpperCamelCase_ ( self: Any, a_: np.ndarray, a_: Union[int, float], a_: Optional[Union[str, ChannelDimension]] = None, **a_: Union[str, Any], ): '''simple docstring''' return rescale(a_, scale=a_, data_format=a_, **a_ ) def UpperCamelCase_ ( self: List[Any], a_: np.ndarray, a_: Union[float, List[float]], a_: Union[float, List[float]], a_: Optional[Union[str, ChannelDimension]] = None, **a_: int, ): '''simple docstring''' return normalize(a_, mean=a_, std=a_, data_format=a_, **a_ ) def UpperCamelCase_ ( self: Dict, a_: ImageInput, a_: bool = None, a_: Dict[str, int] = None, a_: Union[str, Any]=None, a_: bool = None, a_: Dict[str, int] = None, a_: bool = None, a_: float = None, a_: bool = None, a_: Optional[Union[float, List[float]]] = None, a_: Optional[Union[float, List[float]]] = None, a_: Optional[Union[str, TensorType]] = None, a_: ChannelDimension = ChannelDimension.FIRST, **a_: Optional[Any], ): '''simple docstring''' _snake_case : Dict = do_resize if do_resize is not None else self.do_resize _snake_case : Optional[Any] = resample if resample is not None else self.resample _snake_case : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop _snake_case : List[Any] = do_rescale if do_rescale is not None else self.do_rescale _snake_case : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor _snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize _snake_case : List[Any] = image_mean if image_mean is not None else self.image_mean _snake_case : Optional[Any] = image_std if image_std is not None else self.image_std _snake_case : Union[str, Any] = size if size is not None else self.size _snake_case : Dict = get_size_dict(a_ ) _snake_case : Dict = crop_size if crop_size is not None else self.crop_size _snake_case : List[Any] = get_size_dict(a_, param_name="""crop_size""" ) _snake_case : List[str] = make_list_of_images(a_ ) if not valid_images(a_ ): 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 or resample is None: raise ValueError("""Size and resample 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. _snake_case : Union[str, Any] = [to_numpy_array(a_ ) for image in images] if do_resize: _snake_case : Optional[int] = [self.resize(image=a_, size=a_, resample=a_ ) for image in images] if do_center_crop: _snake_case : Any = [self.center_crop(image=a_, size=a_ ) for image in images] if do_rescale: _snake_case : Optional[Any] = [self.rescale(image=a_, scale=a_ ) for image in images] if do_normalize: _snake_case : List[Any] = [self.normalize(image=a_, mean=a_, std=a_ ) for image in images] _snake_case : int = [to_channel_dimension_format(a_, a_ ) for image in images] _snake_case : int = {"""pixel_values""": images} return BatchFeature(data=a_, tensor_type=a_ )
64
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings A_ = r''' [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: title_sep (`str`, *optional*, defaults to `" / "`): Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`]. doc_sep (`str`, *optional*, defaults to `" // "`): Separator inserted between the text of the retrieved document and the original input when calling [`RagRetriever`]. n_docs (`int`, *optional*, defaults to 5): Number of documents to retrieve. max_combined_length (`int`, *optional*, defaults to 300): Max length of contextualized input returned by [`~RagRetriever.__call__`]. retrieval_vector_size (`int`, *optional*, defaults to 768): Dimensionality of the document embeddings indexed by [`RagRetriever`]. retrieval_batch_size (`int`, *optional*, defaults to 8): Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated [`RagRetriever`]. dataset (`str`, *optional*, defaults to `"wiki_dpr"`): A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids using `datasets.list_datasets()`). dataset_split (`str`, *optional*, defaults to `"train"`) Which split of the `dataset` to load. index_name (`str`, *optional*, defaults to `"compressed"`) The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and `"compressed"`. index_path (`str`, *optional*) The path to the serialized faiss index on disk. passages_path (`str`, *optional*): A path to text passages compatible with the faiss index. Required if using [`~models.rag.retrieval_rag.LegacyIndex`] use_dummy_dataset (`bool`, *optional*, defaults to `False`) Whether to load a "dummy" variant of the dataset specified by `dataset`. label_smoothing (`float`, *optional*, defaults to 0.0): Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed. do_marginalize (`bool`, *optional*, defaults to `False`): If `True`, the logits are marginalized over all documents by making use of `torch.nn.functional.log_softmax`. reduce_loss (`bool`, *optional*, defaults to `False`): Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation. do_deduplication (`bool`, *optional*, defaults to `True`): Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to `False` if used while training with distributed backend. exclude_bos_score (`bool`, *optional*, defaults to `False`): Whether or not to disregard the BOS token when computing the loss. output_retrieved(`bool`, *optional*, defaults to `False`): If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and `context_attention_mask` are returned. See returned tensors for more detail. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). forced_eos_token_id (`int`, *optional*): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`. ''' @add_start_docstrings(__a ) class lowercase( __a ): '''simple docstring''' lowercase__ = "rag" lowercase__ = True def __init__( self: Union[str, Any], a_: int=None, a_: Tuple=True, a_: Optional[int]=None, a_: List[str]=None, a_: int=None, a_: Optional[Any]=None, a_: List[str]=None, a_: Optional[Any]=" / ", a_: Tuple=" // ", a_: List[Any]=5, a_: Dict=300, a_: Tuple=768, a_: Optional[Any]=8, a_: int="wiki_dpr", a_: Any="train", a_: Optional[int]="compressed", a_: Optional[int]=None, a_: List[Any]=None, a_: Optional[Any]=False, a_: str=False, a_: Dict=0.0, a_: Union[str, Any]=True, a_: Union[str, Any]=False, a_: str=False, a_: List[str]=False, a_: Union[str, Any]=True, a_: Any=None, **a_: List[Any], ): '''simple docstring''' super().__init__( bos_token_id=a_, pad_token_id=a_, eos_token_id=a_, decoder_start_token_id=a_, forced_eos_token_id=a_, is_encoder_decoder=a_, prefix=a_, vocab_size=a_, **a_, ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _snake_case : Union[str, Any] = kwargs.pop("""question_encoder""" ) _snake_case : List[str] = question_encoder_config.pop("""model_type""" ) _snake_case : Union[str, Any] = kwargs.pop("""generator""" ) _snake_case : Any = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig _snake_case : Union[str, Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Optional[Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Any = reduce_loss _snake_case : Optional[int] = label_smoothing _snake_case : Dict = exclude_bos_score _snake_case : int = do_marginalize _snake_case : Optional[Any] = title_sep _snake_case : Any = doc_sep _snake_case : List[str] = n_docs _snake_case : Tuple = max_combined_length _snake_case : Optional[Any] = dataset _snake_case : Union[str, Any] = dataset_split _snake_case : Tuple = index_name _snake_case : Any = retrieval_vector_size _snake_case : Union[str, Any] = retrieval_batch_size _snake_case : str = passages_path _snake_case : Tuple = index_path _snake_case : List[Any] = use_dummy_dataset _snake_case : Optional[Any] = output_retrieved _snake_case : Tuple = do_deduplication _snake_case : Union[str, Any] = use_cache if self.forced_eos_token_id is None: _snake_case : Dict = getattr(self.generator, """forced_eos_token_id""", a_ ) @classmethod def UpperCamelCase_ ( cls: Any, a_: PretrainedConfig, a_: PretrainedConfig, **a_: Optional[Any] ): '''simple docstring''' return cls(question_encoder=question_encoder_config.to_dict(), generator=generator_config.to_dict(), **a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Optional[int] = copy.deepcopy(self.__dict__ ) _snake_case : List[str] = self.question_encoder.to_dict() _snake_case : Tuple = self.generator.to_dict() _snake_case : Dict = self.__class__.model_type return output
64
1
"""simple docstring""" from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING A_ = logging.get_logger(__name__) @add_end_docstrings(__a ) class lowercase( __a ): '''simple docstring''' def __init__( self: Optional[Any], *a_: Dict, **a_: int ): '''simple docstring''' super().__init__(*a_, **a_ ) requires_backends(self, """decord""" ) self.check_model_type(a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: str=None, a_: Any=None, a_: Optional[int]=None ): '''simple docstring''' _snake_case : List[str] = {} if frame_sampling_rate is not None: _snake_case : str = frame_sampling_rate if num_frames is not None: _snake_case : List[str] = num_frames _snake_case : Optional[Any] = {} if top_k is not None: _snake_case : Tuple = top_k return preprocess_params, {}, postprocess_params def __call__( self: Union[str, Any], a_: Union[str, List[str]], **a_: Tuple ): '''simple docstring''' return super().__call__(a_, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: List[str], a_: Optional[int]=None, a_: Optional[int]=1 ): '''simple docstring''' if num_frames is None: _snake_case : Optional[Any] = self.model.config.num_frames if video.startswith("""http://""" ) or video.startswith("""https://""" ): _snake_case : Tuple = BytesIO(requests.get(a_ ).content ) _snake_case : Union[str, Any] = VideoReader(a_ ) videoreader.seek(0 ) _snake_case : Union[str, Any] = 0 _snake_case : List[str] = num_frames * frame_sampling_rate - 1 _snake_case : Dict = np.linspace(a_, a_, num=a_, dtype=np.intaa ) _snake_case : str = videoreader.get_batch(a_ ).asnumpy() _snake_case : Union[str, Any] = list(a_ ) _snake_case : Union[str, Any] = self.image_processor(a_, return_tensors=self.framework ) return model_inputs def UpperCamelCase_ ( self: str, a_: str ): '''simple docstring''' _snake_case : List[Any] = self.model(**a_ ) return model_outputs def UpperCamelCase_ ( self: Union[str, Any], a_: List[str], a_: str=5 ): '''simple docstring''' if top_k > self.model.config.num_labels: _snake_case : Optional[int] = self.model.config.num_labels if self.framework == "pt": _snake_case : Tuple = model_outputs.logits.softmax(-1 )[0] _snake_case , _snake_case : List[Any] = probs.topk(a_ ) else: raise ValueError(f"Unsupported framework: {self.framework}" ) _snake_case : str = scores.tolist() _snake_case : str = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(a_, a_ )]
64
"""simple docstring""" import os from typing import Dict, List, Tuple, TypeVar, Union A_ = TypeVar('''T''') A_ = Union[List[T], Tuple[T, ...]] A_ = Union[T, List[T], Dict[str, T]] A_ = Union[str, bytes, os.PathLike]
64
1
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable A_ = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] _snake_case : List[Any] = [] def generate(snake_case__ : int , snake_case__ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even _snake_case , _snake_case : Optional[Any] = arr[k - 1], arr[i] else: # k is odd _snake_case , _snake_case : List[str] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
64
1
"""simple docstring""" import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 A_ = data_utils.TransfoXLTokenizer A_ = data_utils.TransfoXLCorpus A_ = data_utils A_ = data_utils def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int , snake_case__ : Optional[Any] ): """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(snake_case__ , """rb""" ) as fp: _snake_case : List[str] = pickle.load(snake_case__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) _snake_case : Union[str, Any] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(F"Save vocabulary to {pytorch_vocab_dump_path}" ) _snake_case : Any = corpus.vocab.__dict__ torch.save(snake_case__ , snake_case__ ) _snake_case : Optional[int] = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , snake_case__ ) _snake_case : str = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(F"Save dataset to {pytorch_dataset_dump_path}" ) torch.save(snake_case__ , snake_case__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model _snake_case : Optional[Any] = os.path.abspath(snake_case__ ) _snake_case : Dict = os.path.abspath(snake_case__ ) print(F"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}." ) # Initialise PyTorch model if transfo_xl_config_file == "": _snake_case : List[Any] = TransfoXLConfig() else: _snake_case : int = TransfoXLConfig.from_json_file(snake_case__ ) print(F"Building PyTorch model from configuration: {config}" ) _snake_case : Tuple = TransfoXLLMHeadModel(snake_case__ ) _snake_case : str = load_tf_weights_in_transfo_xl(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model _snake_case : int = os.path.join(snake_case__ , snake_case__ ) _snake_case : int = os.path.join(snake_case__ , snake_case__ ) print(F"Save PyTorch model to {os.path.abspath(snake_case__ )}" ) torch.save(model.state_dict() , snake_case__ ) print(F"Save configuration file to {os.path.abspath(snake_case__ )}" ) with open(snake_case__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the folder to store the PyTorch model or dataset/vocab.''', ) parser.add_argument( '''--tf_checkpoint_path''', default='''''', type=str, help='''An optional path to a TensorFlow checkpoint path to be converted.''', ) parser.add_argument( '''--transfo_xl_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--transfo_xl_dataset_file''', default='''''', type=str, help='''An optional dataset file to be converted in a vocabulary.''', ) A_ = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
64
"""simple docstring""" from math import factorial A_ = {str(d): factorial(d) for d in range(10)} def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , snake_case__ ) if sum_of_digit_factorial(snake_case__ ) == i ) if __name__ == "__main__": print(F'''{solution() = }''')
64
1
"""simple docstring""" import itertools import math def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" 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(snake_case__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = 2 while True: if is_prime(snake_case__ ): yield num num += 1 def UpperCAmelCase__ (snake_case__ : int = 1_00_01 ): """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , snake_case__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
64
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : int ): """simple docstring""" if len(snake_case__ ) < k or k < 0: raise ValueError("""Invalid Input""" ) _snake_case : Optional[int] = sum(array[:k] ) for i in range(len(snake_case__ ) - k ): _snake_case : Optional[Any] = current_sum - array[i] + array[i + k] _snake_case : List[str] = max(snake_case__ , snake_case__ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() A_ = [randint(-10_00, 10_00) for i in range(1_00)] A_ = randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
64
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } A_ = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } A_ = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = BertTokenizer def __init__( self: int, a_: Any=None, a_: Tuple=None, a_: Tuple=True, a_: Union[str, Any]="[UNK]", a_: List[Any]="[SEP]", a_: Union[str, Any]="[PAD]", a_: List[str]="[CLS]", a_: Union[str, Any]="[MASK]", a_: List[str]=True, a_: List[str]=None, **a_: List[Any], ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Optional[int] = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : Optional[Any] = do_lower_case _snake_case : Optional[int] = strip_accents _snake_case : int = tokenize_chinese_chars _snake_case : Union[str, Any] = normalizer_class(**a_ ) _snake_case : str = do_lower_case def UpperCamelCase_ ( self: Dict, a_: Dict, a_: str=None ): '''simple docstring''' _snake_case : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: Any, a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Dict = [self.sep_token_id] _snake_case : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: Union[str, Any], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : List[Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } A_ = { '''yjernite/retribert-base-uncased''': 5_12, } A_ = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = RetriBertTokenizer lowercase__ = ["input_ids", "attention_mask"] def __init__( self: int, a_: int=None, a_: Dict=None, a_: Any=True, a_: int="[UNK]", a_: Any="[SEP]", a_: List[Any]="[PAD]", a_: List[Any]="[CLS]", a_: str="[MASK]", a_: Dict=True, a_: Optional[int]=None, **a_: Tuple, ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Dict = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : List[Any] = do_lower_case _snake_case : List[str] = strip_accents _snake_case : Tuple = tokenize_chinese_chars _snake_case : Tuple = normalizer_class(**a_ ) _snake_case : List[str] = do_lower_case def UpperCamelCase_ ( self: Any, a_: str, a_: Optional[int]=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: List[str], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: Dict, a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : Union[str, Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
1
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowercase( enum.Enum ): '''simple docstring''' lowercase__ = 0 lowercase__ = 1 lowercase__ = 2 @add_end_docstrings(__a ) class lowercase( __a ): '''simple docstring''' lowercase__ = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self: List[Any], *a_: int, **a_: str ): '''simple docstring''' super().__init__(*a_, **a_ ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _snake_case : str = None if self.model.config.prefix is not None: _snake_case : Optional[Any] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _snake_case : Any = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _snake_case , _snake_case , _snake_case : List[str] = self._sanitize_parameters(prefix=a_, **self._forward_params ) _snake_case : Dict = {**self._preprocess_params, **preprocess_params} _snake_case : Dict = {**self._forward_params, **forward_params} def UpperCamelCase_ ( self: Any, a_: Optional[int]=None, a_: str=None, a_: Optional[int]=None, a_: str=None, a_: Dict=None, a_: Tuple=None, a_: Tuple=None, a_: List[Any]=None, **a_: int, ): '''simple docstring''' _snake_case : str = {} if prefix is not None: _snake_case : List[Any] = prefix if prefix: _snake_case : List[Any] = self.tokenizer( a_, padding=a_, add_special_tokens=a_, return_tensors=self.framework ) _snake_case : List[Any] = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" """ [None, 'hole']""" ) _snake_case : List[Any] = handle_long_generation preprocess_params.update(a_ ) _snake_case : Optional[Any] = generate_kwargs _snake_case : Tuple = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) _snake_case : int = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) _snake_case : Union[str, Any] = ReturnType.TENSORS if return_type is not None: _snake_case : List[str] = return_type if clean_up_tokenization_spaces is not None: _snake_case : str = clean_up_tokenization_spaces if stop_sequence is not None: _snake_case : Dict = self.tokenizer.encode(a_, add_special_tokens=a_ ) if len(a_ ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) _snake_case : Optional[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCamelCase_ ( self: Dict, *a_: str, **a_: Union[str, Any] ): '''simple docstring''' if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*a_, **a_ ) def __call__( self: List[Any], a_: Dict, **a_: List[str] ): '''simple docstring''' return super().__call__(a_, **a_ ) def UpperCamelCase_ ( self: Any, a_: int, a_: List[Any]="", a_: Tuple=None, **a_: Tuple ): '''simple docstring''' _snake_case : List[Any] = self.tokenizer( prefix + prompt_text, padding=a_, add_special_tokens=a_, return_tensors=self.framework ) _snake_case : int = prompt_text if handle_long_generation == "hole": _snake_case : Union[str, Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: _snake_case : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: _snake_case : Union[str, Any] = generate_kwargs.get("""max_length""", self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: _snake_case : List[Any] = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) _snake_case : int = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: _snake_case : List[str] = inputs["""attention_mask"""][:, -keep_length:] return inputs def UpperCamelCase_ ( self: int, a_: Any, **a_: List[str] ): '''simple docstring''' _snake_case : int = model_inputs["""input_ids"""] _snake_case : str = model_inputs.get("""attention_mask""", a_ ) # Allow empty prompts if input_ids.shape[1] == 0: _snake_case : Any = None _snake_case : int = None _snake_case : Union[str, Any] = 1 else: _snake_case : List[Any] = input_ids.shape[0] _snake_case : Optional[int] = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _snake_case : Any = generate_kwargs.pop("""prefix_length""", 0 ) if prefix_length > 0: _snake_case : str = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: _snake_case : Dict = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _snake_case : Any = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _snake_case : Dict = self.model.generate(input_ids=a_, attention_mask=a_, **a_ ) _snake_case : Union[str, Any] = generated_sequence.shape[0] if self.framework == "pt": _snake_case : List[Any] = generated_sequence.reshape(a_, out_b // in_b, *generated_sequence.shape[1:] ) elif self.framework == "tf": _snake_case : Optional[int] = tf.reshape(a_, (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def UpperCamelCase_ ( self: Optional[Any], a_: Dict, a_: Any=ReturnType.FULL_TEXT, a_: Union[str, Any]=True ): '''simple docstring''' _snake_case : Optional[int] = model_outputs["""generated_sequence"""][0] _snake_case : Any = model_outputs["""input_ids"""] _snake_case : int = model_outputs["""prompt_text"""] _snake_case : Optional[Any] = generated_sequence.numpy().tolist() _snake_case : str = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _snake_case : Union[str, Any] = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _snake_case : List[str] = self.tokenizer.decode( a_, skip_special_tokens=a_, clean_up_tokenization_spaces=a_, ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _snake_case : str = 0 else: _snake_case : Optional[Any] = len( self.tokenizer.decode( input_ids[0], skip_special_tokens=a_, clean_up_tokenization_spaces=a_, ) ) if return_type == ReturnType.FULL_TEXT: _snake_case : Optional[int] = prompt_text + text[prompt_length:] else: _snake_case : int = text[prompt_length:] _snake_case : List[Any] = {"""generated_text""": all_text} records.append(a_ ) return records
64
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CodeGenTokenizer lowercase__ = CodeGenTokenizerFast lowercase__ = True lowercase__ = {"add_prefix_space": True} lowercase__ = False def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _snake_case : Tuple = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] _snake_case : Tuple = dict(zip(a_, range(len(a_ ) ) ) ) _snake_case : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _snake_case : List[Any] = {"""unk_token""": """<unk>"""} _snake_case : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) _snake_case : Optional[Any] = 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(a_ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(a_ ) ) def UpperCamelCase_ ( self: Any, **a_: int ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Any, **a_: str ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Dict ): '''simple docstring''' _snake_case : Union[str, Any] = """lower newer""" _snake_case : Tuple = """lower newer""" return input_text, output_text def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) _snake_case : Optional[Any] = """lower newer""" _snake_case : Optional[int] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] _snake_case : int = tokenizer.tokenize(a_, add_prefix_space=a_ ) self.assertListEqual(a_, a_ ) _snake_case : str = tokens + [tokenizer.unk_token] _snake_case : Optional[int] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : int = self.get_tokenizer() _snake_case : int = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : Dict = """lower newer""" # Testing tokenization _snake_case : Dict = tokenizer.tokenize(a_, add_prefix_space=a_ ) _snake_case : List[str] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids without special tokens _snake_case : Optional[Any] = tokenizer.encode(a_, add_special_tokens=a_, add_prefix_space=a_ ) _snake_case : Tuple = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids with special tokens _snake_case : Tuple = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : int = tokenizer.encode(a_, add_prefix_space=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) # Testing the unknown token _snake_case : Tuple = tokens + [rust_tokenizer.unk_token] _snake_case : List[Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Dict, *a_: Dict, **a_: int ): '''simple docstring''' pass def UpperCamelCase_ ( self: int, a_: List[Any]=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : List[Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) # Simple input _snake_case : Any = """This is a simple input""" _snake_case : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Optional[int] = ("""This is a simple input""", """This is a pair""") _snake_case : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) # Pair input self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token="""<pad>""" ) # Simple input _snake_case : List[Any] = """This is a simple input""" _snake_case : int = ["""This is a simple input looooooooong""", """This is a simple input"""] _snake_case : Any = ("""This is a simple input""", """This is a pair""") _snake_case : str = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] _snake_case : str = tokenizer.pad_token_id _snake_case : Optional[int] = tokenizer(a_, padding="""max_length""", max_length=30, return_tensors="""np""" ) _snake_case : Dict = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) _snake_case : Tuple = tokenizer(*a_, padding="""max_length""", max_length=60, return_tensors="""np""" ) _snake_case : Optional[Any] = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Tuple = """$$$""" _snake_case : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=a_, add_bos_token=a_ ) _snake_case : str = """This is a simple input""" _snake_case : int = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Tuple = tokenizer(a_ ) _snake_case : Optional[Any] = tokenizer(a_ ) self.assertEqual(out_s.input_ids[0], a_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) _snake_case : Optional[int] = tokenizer.decode(out_s.input_ids ) _snake_case : int = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], a_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) _snake_case : Dict = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" _snake_case : Union[str, Any] = """\nif len_a > len_b: result = a\nelse: result = b""" _snake_case : Optional[Any] = tokenizer.encode(a_ ) _snake_case : Dict = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] _snake_case : Optional[Any] = tokenizer.decode(a_, truncate_before_pattern=a_ ) self.assertEqual(a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' pass
64
1
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class lowercase( __a ): '''simple docstring''' lowercase__ = "" lowercase__ = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowercase__ = None # compression type in fsspec. ex: "gzip" lowercase__ = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self: Dict, a_: str = "", a_: Optional[str] = None, a_: Optional[dict] = None, **a_: str ): '''simple docstring''' super().__init__(self, **a_ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode _snake_case : Dict = fsspec.open( a_, mode="""rb""", protocol=a_, compression=self.compression, client_kwargs={ """requote_redirect_url""": False, # see https://github.com/huggingface/datasets/pull/5459 """trust_env""": True, # Enable reading proxy env variables. **(target_options or {}).pop("""client_kwargs""", {} ), # To avoid issues if it was already passed. }, **(target_options or {}), ) _snake_case : List[str] = os.path.basename(self.file.path.split("""::""" )[0] ) _snake_case : List[str] = ( self.compressed_name[: self.compressed_name.rindex(""".""" )] if """.""" in self.compressed_name else self.compressed_name ) _snake_case : List[Any] = None @classmethod def UpperCamelCase_ ( cls: Dict, a_: List[str] ): '''simple docstring''' return super()._strip_protocol(a_ ).lstrip("""/""" ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' if self.dir_cache is None: _snake_case : List[Any] = {**self.file.fs.info(self.file.path ), """name""": self.uncompressed_name} _snake_case : Union[str, Any] = {f["""name"""]: f} def UpperCamelCase_ ( self: int, a_: str ): '''simple docstring''' return self.file.open().read() def UpperCamelCase_ ( self: List[Any], a_: str, a_: str = "rb", a_: str=None, a_: Optional[int]=True, a_: Any=None, **a_: List[Any], ): '''simple docstring''' _snake_case : str = self._strip_protocol(a_ ) if mode != "rb": raise ValueError(f"Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'" ) return self.file.open() class lowercase( __a ): '''simple docstring''' lowercase__ = "bz2" lowercase__ = "bz2" lowercase__ = ".bz2" class lowercase( __a ): '''simple docstring''' lowercase__ = "gzip" lowercase__ = "gzip" lowercase__ = ".gz" class lowercase( __a ): '''simple docstring''' lowercase__ = "lz4" lowercase__ = "lz4" lowercase__ = ".lz4" class lowercase( __a ): '''simple docstring''' lowercase__ = "xz" lowercase__ = "xz" lowercase__ = ".xz" class lowercase( __a ): '''simple docstring''' lowercase__ = "zstd" lowercase__ = "zstd" lowercase__ = ".zst" def __init__( self: List[str], a_: str, a_: str = "rb", a_: Optional[str] = None, a_: Optional[dict] = None, a_: int = DEFAULT_BLOCK_SIZE, **a_: Optional[Any], ): '''simple docstring''' super().__init__( fo=a_, mode=a_, target_protocol=a_, target_options=a_, block_size=a_, **a_, ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 _snake_case : Any = self.file.__enter__ class lowercase: '''simple docstring''' def __init__( self: Union[str, Any], a_: List[Any] ): '''simple docstring''' _snake_case : Tuple = file_ def __enter__( self: List[str] ): '''simple docstring''' self._file.__enter__() return self def __exit__( self: int, *a_: List[str], **a_: Optional[int] ): '''simple docstring''' self._file.__exit__(*a_, **a_ ) def __iter__( self: int ): '''simple docstring''' return iter(self._file ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' return next(self._file ) def __getattr__( self: Optional[Any], a_: Optional[Any] ): '''simple docstring''' return getattr(self._file, a_ ) def fixed_enter(*a_: Any, **a_: Optional[int] ): return WrappedFile(_enter(*a_, **a_ ) ) _snake_case : Union[str, Any] = fixed_enter
64
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser A_ = re.compile(r'''\s+''') def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" return {"hash": hashlib.mda(re.sub(snake_case__ , """""" , example["""content"""] ).encode("""utf-8""" ) ).hexdigest()} def UpperCAmelCase__ (snake_case__ : Dict ): """simple docstring""" _snake_case : Any = [len(snake_case__ ) for line in example["""content"""].splitlines()] return {"line_mean": np.mean(snake_case__ ), "line_max": max(snake_case__ )} def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" _snake_case : Tuple = np.mean([c.isalnum() for c in example["""content"""]] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : List[Any] ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example["""hash"""] ) return True else: return False def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : List[str]=5 ): """simple docstring""" _snake_case : Any = ["""auto-generated""", """autogenerated""", """automatically generated"""] _snake_case : Tuple = example["""content"""].splitlines() for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Union[str, Any]=5 , snake_case__ : Any=0.05 ): """simple docstring""" _snake_case : Optional[Any] = ["""unit tests""", """test file""", """configuration file"""] _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : Dict = 0 _snake_case : str = 0 # first test for _, line in zip(range(snake_case__ ) , snake_case__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _snake_case : Optional[int] = example["""content"""].count("""\n""" ) _snake_case : Tuple = int(coeff * nlines ) for line in lines: count_config += line.lower().count("""config""" ) count_test += line.lower().count("""test""" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Optional[int] = ["""def """, """class """, """for """, """while """] _snake_case : str = example["""content"""].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase__ (snake_case__ : List[str] , snake_case__ : List[str]=4 ): """simple docstring""" _snake_case : List[Any] = example["""content"""].splitlines() _snake_case : str = 0 for line in lines: counter += line.lower().count("""=""" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase__ (snake_case__ : List[str] ): """simple docstring""" _snake_case : Optional[Any] = tokenizer(example["""content"""] , truncation=snake_case__ )["""input_ids"""] _snake_case : Optional[Any] = len(example["""content"""] ) / len(snake_case__ ) return {"ratio": ratio} def UpperCAmelCase__ (snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[int] = {} results.update(get_hash(snake_case__ ) ) results.update(line_stats(snake_case__ ) ) results.update(alpha_stats(snake_case__ ) ) results.update(char_token_ratio(snake_case__ ) ) results.update(is_autogenerated(snake_case__ ) ) results.update(is_config_or_test(snake_case__ ) ) results.update(has_no_keywords(snake_case__ ) ) results.update(has_few_assignments(snake_case__ ) ) return results def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : List[str] ): """simple docstring""" if not check_uniques(snake_case__ , snake_case__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" with open(snake_case__ , """rb""" ) as f_in: with gzip.open(str(snake_case__ ) + """.gz""" , """wb""" , compresslevel=6 ) as f_out: shutil.copyfileobj(snake_case__ , snake_case__ ) os.unlink(snake_case__ ) # Settings A_ = HfArgumentParser(PreprocessingArguments) A_ = parser.parse_args() if args.num_workers is None: A_ = multiprocessing.cpu_count() A_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset A_ = time.time() A_ = load_dataset(args.dataset_name, split='''train''') print(F'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing A_ = time.time() A_ = ds.map(preprocess, num_proc=args.num_workers) print(F'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes A_ = set(ds.unique('''hash''')) A_ = len(uniques) / len(ds) print(F'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics A_ = time.time() A_ = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F'''Time to filter dataset: {time.time()-t_start:.2f}''') print(F'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: A_ = time.time() A_ , A_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(F'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file A_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) A_ = output_dir / '''data''' data_dir.mkdir(exist_ok=True) A_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): A_ = str(data_dir / F'''file-{file_number+1:012}.json''') A_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'''Time to save dataset: {time.time()-t_start:.2f}''')
64
1
"""simple docstring""" import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : Any , snake_case__ : List[str] , snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : Dict = original_name.split(""".""" )[0] _snake_case : Union[str, Any] = key.split(""".""" ) _snake_case : Optional[Any] = int(key_list[key_list.index(snake_case__ ) - 2] ) _snake_case : str = int(key_list[key_list.index(snake_case__ ) - 1] ) _snake_case : Any = orig_block_num - offset _snake_case : List[str] = key.replace(F"{orig_block_num}.{layer_num}.{original_name}" , F"block.{new_block_num}.{layer_num}.{new_name}" ) return key def UpperCAmelCase__ (snake_case__ : Tuple ): """simple docstring""" _snake_case : int = OrderedDict() _snake_case , _snake_case : Union[str, Any] = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): _snake_case : int = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 _snake_case : Optional[int] = key[: key.find("""proj""" )] _snake_case : List[Any] = key.replace(snake_case__ , F"patch_embeddings.{total_embed_found}." ) _snake_case : Dict = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: _snake_case : Tuple = """poolformer.encoder.""" + key if "mlp.fc1" in key: _snake_case : int = replace_key_with_offset(snake_case__ , snake_case__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: _snake_case : Dict = replace_key_with_offset(snake_case__ , snake_case__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: _snake_case : Tuple = replace_key_with_offset(snake_case__ , snake_case__ , """norm1""" , """before_norm""" ) if "norm2" in key: _snake_case : Dict = replace_key_with_offset(snake_case__ , snake_case__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: _snake_case : Optional[int] = replace_key_with_offset(snake_case__ , snake_case__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: _snake_case : int = replace_key_with_offset(snake_case__ , snake_case__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: _snake_case : Optional[int] = key.replace("""head""" , """classifier""" ) _snake_case : List[Any] = value return new_state_dict def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : List[str] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return image @torch.no_grad() def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : Optional[int] , snake_case__ : Dict ): """simple docstring""" _snake_case : Optional[int] = PoolFormerConfig() # set attributes based on model_name _snake_case : Tuple = """huggingface/label-files""" _snake_case : int = model_name[-3:] _snake_case : List[Any] = 10_00 _snake_case : List[str] = """imagenet-1k-id2label.json""" _snake_case : Any = (1, 10_00) # set config attributes _snake_case : Union[str, Any] = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="""dataset""" ) , """r""" ) ) _snake_case : List[Any] = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[str] = idalabel _snake_case : List[Any] = {v: k for k, v in idalabel.items()} if size == "s12": _snake_case : Dict = [2, 2, 6, 2] _snake_case : Dict = [64, 1_28, 3_20, 5_12] _snake_case : Dict = 4.0 _snake_case : Tuple = 0.9 elif size == "s24": _snake_case : Tuple = [4, 4, 12, 4] _snake_case : int = [64, 1_28, 3_20, 5_12] _snake_case : List[Any] = 4.0 _snake_case : int = 0.9 elif size == "s36": _snake_case : Tuple = [6, 6, 18, 6] _snake_case : Optional[int] = [64, 1_28, 3_20, 5_12] _snake_case : Optional[int] = 4.0 _snake_case : Union[str, Any] = 1e-6 _snake_case : List[str] = 0.9 elif size == "m36": _snake_case : Any = [6, 6, 18, 6] _snake_case : Union[str, Any] = [96, 1_92, 3_84, 7_68] _snake_case : Any = 4.0 _snake_case : Union[str, Any] = 1e-6 _snake_case : int = 0.95 elif size == "m48": _snake_case : Dict = [8, 8, 24, 8] _snake_case : Optional[int] = [96, 1_92, 3_84, 7_68] _snake_case : Optional[int] = 4.0 _snake_case : Dict = 1e-6 _snake_case : List[Any] = 0.95 else: raise ValueError(F"Size {size} not supported" ) # load image processor _snake_case : str = PoolFormerImageProcessor(crop_pct=snake_case__ ) # Prepare image _snake_case : Dict = prepare_img() _snake_case : Optional[int] = image_processor(images=snake_case__ , return_tensors="""pt""" ).pixel_values logger.info(F"Converting model {model_name}..." ) # load original state dict _snake_case : int = torch.load(snake_case__ , map_location=torch.device("""cpu""" ) ) # rename keys _snake_case : Tuple = rename_keys(snake_case__ ) # create HuggingFace model and load state dict _snake_case : str = PoolFormerForImageClassification(snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() # Define image processor _snake_case : Union[str, Any] = PoolFormerImageProcessor(crop_pct=snake_case__ ) _snake_case : Optional[Any] = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass _snake_case : List[Any] = model(snake_case__ ) _snake_case : Tuple = outputs.logits # define expected logit slices for different models if size == "s12": _snake_case : List[str] = torch.tensor([-0.30_45, -0.67_58, -0.48_69] ) elif size == "s24": _snake_case : Any = torch.tensor([0.44_02, -0.13_74, -0.80_45] ) elif size == "s36": _snake_case : List[Any] = torch.tensor([-0.60_80, -0.51_33, -0.58_98] ) elif size == "m36": _snake_case : List[str] = torch.tensor([0.39_52, 0.22_63, -1.26_68] ) elif size == "m48": _snake_case : Union[str, Any] = torch.tensor([0.11_67, -0.06_56, -0.34_23] ) else: raise ValueError(F"Size {size} not supported" ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , snake_case__ , atol=1e-2 ) # finally, save model and image processor logger.info(F"Saving PyTorch model and image processor to {pytorch_dump_folder_path}..." ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) A_ = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
64
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase( unittest.TestCase ): '''simple docstring''' @property def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Any = ort.SessionOptions() _snake_case : Union[str, Any] = False return options def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _snake_case : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _snake_case : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _snake_case : Optional[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""", revision="""onnx""", safety_checker=a_, feature_extractor=a_, provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : Optional[Any] = """A red cat sitting on a park bench""" _snake_case : Optional[int] = np.random.RandomState(0 ) _snake_case : Any = pipe( prompt=a_, image=a_, mask_image=a_, strength=0.75, guidance_scale=7.5, num_inference_steps=15, generator=a_, output_type="""np""", ) _snake_case : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
64
1
import os from collections import deque import torch from torch.utils.data import Dataset class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : str , __UpperCAmelCase : Dict="" , __UpperCAmelCase : Optional[int]="train" ) ->Tuple: """simple docstring""" assert os.path.isdir(__UpperCAmelCase ) a = [] a = os.listdir(__UpperCAmelCase ) for story_filename in story_filenames_list: if "summary" in story_filename: continue a = os.path.join(__UpperCAmelCase , __UpperCAmelCase ) if not os.path.isfile(__UpperCAmelCase ): continue self.documents.append(__UpperCAmelCase ) def __len__( self : str ) ->Tuple: """simple docstring""" return len(self.documents ) def __getitem__( self : Dict , __UpperCAmelCase : str ) ->Any: """simple docstring""" a = self.documents[idx] a = document_path.split('''/''' )[-1] with open(__UpperCAmelCase , encoding='''utf-8''' ) as source: a = source.read() a , a = process_story(__UpperCAmelCase ) return document_name, story_lines, summary_lines def _a ( a :Tuple ) -> Union[str, Any]: a = list(filter(lambda a : len(a ) != 0 , [line.strip() for line in raw_story.split('''\n''' )] ) ) # for some unknown reason some lines miss a period, add it a = [_add_missing_period(a ) for line in nonempty_lines] # gather article lines a = [] a = deque(a ) while True: try: a = lines.popleft() if element.startswith('''@highlight''' ): break story_lines.append(a ) except IndexError: # if "@highlight" is absent from the file we pop # all elements until there is None, raising an exception. return story_lines, [] # gather summary lines a = list(filter(lambda a : not t.startswith('''@highlight''' ) , a ) ) return story_lines, summary_lines def _a ( a :List[str] ) -> Union[str, Any]: a = ['''.''', '''!''', '''?''', '''...''', '''\'''', '''`''', '''"''', '''\u2019''', '''\u2019''', ''')'''] if line.startswith('''@highlight''' ): return line if line[-1] in END_TOKENS: return line return line + "." def _a ( a :Optional[Any] , a :int , a :Union[str, Any] ) -> Optional[int]: if len(a ) > block_size: return sequence[:block_size] else: sequence.extend([pad_token_id] * (block_size - len(a )) ) return sequence def _a ( a :Union[str, Any] , a :Optional[int] ) -> Union[str, Any]: a = torch.ones_like(a ) a = sequence == pad_token_id a = 0 return mask def _a ( a :Optional[Any] , a :Optional[Any] , a :Tuple ) -> List[Any]: a = [tokenizer.encode(a ) for line in story_lines] a = [token for sentence in story_lines_token_ids for token in sentence] a = [tokenizer.encode(a ) for line in summary_lines] a = [token for sentence in summary_lines_token_ids for token in sentence] return story_token_ids, summary_token_ids def _a ( a :int , a :str ) -> Dict: a = [] for sequence in batch: a = -1 a = [] for s in sequence: if s == separator_token_id: sentence_num += 1 embeddings.append(sentence_num % 2 ) batch_embeddings.append(a ) return torch.tensor(a )
0
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() A_ = logging.get_logger(__name__) A_ = { '''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''', '''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''', } A_ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Dict , snake_case__ : Any , snake_case__ : str , snake_case__ : str ): """simple docstring""" for attribute in key.split(""".""" ): _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ) if weight_type is not None: _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ).shape else: _snake_case : Optional[Any] = hf_pointer.shape assert hf_shape == value.shape, ( 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": _snake_case : int = value elif weight_type == "weight_g": _snake_case : str = value elif weight_type == "weight_v": _snake_case : Tuple = value elif weight_type == "bias": _snake_case : List[str] = value else: _snake_case : int = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str] ): """simple docstring""" _snake_case : List[Any] = [] _snake_case : Optional[Any] = fairseq_model.state_dict() _snake_case : str = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _snake_case : Optional[Any] = None for name, value in fairseq_dict.items(): _snake_case : Optional[Any] = False if "conv_layers" in name: load_conv_layer( snake_case__ , snake_case__ , snake_case__ , snake_case__ , hf_model.config.feat_extract_norm == """group""" , ) _snake_case : Dict = True elif name.split(""".""" )[0] == "proj": _snake_case : Dict = fairseq_model.proj _snake_case : Optional[int] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _snake_case : Dict = True if "*" in mapped_key: _snake_case : Optional[int] = name.split(snake_case__ )[0].split(""".""" )[-2] _snake_case : Union[str, Any] = mapped_key.replace("""*""" , snake_case__ ) if "weight_g" in name: _snake_case : str = """weight_g""" elif "weight_v" in name: _snake_case : Optional[Any] = """weight_v""" elif "bias" in name: _snake_case : Union[str, Any] = """bias""" elif "weight" in name: _snake_case : int = """weight""" else: _snake_case : Optional[int] = None set_recursively(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) continue if not is_used: unused_weights.append(snake_case__ ) logger.warning(F"Unused weights: {unused_weights}" ) return proj_weight def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : int ): """simple docstring""" _snake_case : Any = full_name.split("""conv_layers.""" )[-1] _snake_case : Optional[int] = name.split(""".""" ) _snake_case : List[str] = int(items[0] ) _snake_case : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _snake_case : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _snake_case : List[Any] = 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _snake_case : int = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _snake_case : List[str] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case , _snake_case : Optional[Any] = emb.weight.shape _snake_case : Optional[int] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _snake_case : Union[str, Any] = emb.weight.data return lin_layer def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" with open(snake_case__ , """r""" , encoding="""utf-8""" ) as f: _snake_case : Any = f.readlines() _snake_case : Optional[Any] = [line.split(""" """ )[0] for line in lines] _snake_case : str = len(snake_case__ ) _snake_case : Tuple = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(snake_case__ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def UpperCAmelCase__ (snake_case__ : int , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Dict , snake_case__ : List[Any] , snake_case__ : str , snake_case__ : Union[str, Any] , ): """simple docstring""" _snake_case : Optional[int] = WavaVecaConfig.from_pretrained(snake_case__ ) _snake_case : List[str] = SpeechaTextaConfig.from_pretrained( snake_case__ , vocab_size=snake_case__ , decoder_layers=snake_case__ , do_stable_layer_norm=snake_case__ ) _snake_case : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case__ , return_attention_mask=snake_case__ , ) _snake_case , _snake_case , _snake_case : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) _snake_case : Optional[Any] = model[0].eval() # set weights for wav2vec2 encoder _snake_case : Any = WavaVecaModel(snake_case__ ) _snake_case : Optional[Any] = recursively_load_weights_wavaveca(model.encoder , snake_case__ ) _snake_case : Optional[Any] = SpeechaTextaForCausalLM(snake_case__ ) _snake_case , _snake_case : List[str] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case__ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) _snake_case : Any = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(F"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) _snake_case : Any = SpeechEncoderDecoderModel(encoder=snake_case__ , decoder=snake_case__ ) _snake_case : Any = False # add projection layer _snake_case : int = nn.Parameter(projection_layer.weight ) _snake_case : Any = nn.Parameter(projection_layer.bias ) _snake_case : Any = create_vocab_dict(snake_case__ ) with open(os.path.join(snake_case__ , """vocab.json""" ) , """w""" ) as fp: json.dump(snake_case__ , snake_case__ ) _snake_case : Dict = SpeechaTextaTokenizer(os.path.join(snake_case__ , """vocab.json""" ) ) tokenizer.save_pretrained(snake_case__ ) _snake_case : str = hf_wavavec.config.to_dict() _snake_case : List[str] = tokenizer.pad_token_id _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Union[str, Any] = tokenizer.eos_token_id _snake_case : Optional[Any] = """speech_to_text_2""" _snake_case : Optional[int] = """wav2vec2""" _snake_case : Tuple = SpeechEncoderDecoderConfig.from_dict(snake_case__ ) hf_wavavec.save_pretrained(snake_case__ ) feature_extractor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = 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( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=1_02_24, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') A_ = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
64
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_: List[str] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Dict ={ 'facebook/nllb-moe-54B': 'https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : Union[str, Any] = """nllb-moe""" a__ : Optional[Any] = ["""past_key_values"""] a__ : Dict = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__(self : Optional[Any] , __a : Tuple=128112 , __a : Optional[int]=1024 , __a : List[str]=12 , __a : int=4096 , __a : str=16 , __a : Any=12 , __a : List[str]=4096 , __a : str=16 , __a : Any=0.05 , __a : str=0.05 , __a : Dict=True , __a : Dict=True , __a : Optional[Any]="relu" , __a : List[str]=1024 , __a : Any=0.1 , __a : Union[str, Any]=0.1 , __a : List[str]=0.0 , __a : int=0.02 , __a : Optional[int]=2 , __a : List[Any]=True , __a : Any=False , __a : List[str]="float32" , __a : List[str]=False , __a : Optional[int]=128 , __a : Any=64 , __a : Any=4 , __a : List[str]=4 , __a : Union[str, Any]=0.0_01 , __a : Optional[Any]=0.0_01 , __a : List[Any]="all" , __a : Tuple=False , __a : Any=False , __a : Dict=1.0 , __a : int=0.2 , __a : Dict=1 , __a : Dict=0 , __a : Optional[int]=2 , __a : Any=False , **__a : Optional[int] , ): UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = d_model UpperCAmelCase_ = encoder_ffn_dim UpperCAmelCase_ = encoder_layers UpperCAmelCase_ = encoder_attention_heads UpperCAmelCase_ = decoder_ffn_dim UpperCAmelCase_ = decoder_layers UpperCAmelCase_ = decoder_attention_heads UpperCAmelCase_ = dropout UpperCAmelCase_ = attention_dropout UpperCAmelCase_ = activation_dropout UpperCAmelCase_ = activation_function UpperCAmelCase_ = init_std UpperCAmelCase_ = encoder_layerdrop UpperCAmelCase_ = decoder_layerdrop UpperCAmelCase_ = use_cache UpperCAmelCase_ = encoder_layers UpperCAmelCase_ = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase_ = router_z_loss_coef UpperCAmelCase_ = router_aux_loss_coef UpperCAmelCase_ = decoder_sparse_step UpperCAmelCase_ = encoder_sparse_step UpperCAmelCase_ = num_experts UpperCAmelCase_ = expert_capacity UpperCAmelCase_ = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) UpperCAmelCase_ = router_dtype UpperCAmelCase_ = router_ignore_padding_tokens UpperCAmelCase_ = batch_prioritized_routing UpperCAmelCase_ = second_expert_policy UpperCAmelCase_ = normalize_router_prob_before_dropping UpperCAmelCase_ = moe_eval_capacity_token_fraction UpperCAmelCase_ = moe_token_dropout UpperCAmelCase_ = output_router_logits super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , decoder_start_token_id=__a , **__a , )
1
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A_ = 16 A_ = 32 def UpperCAmelCase__ (snake_case__ : Accelerator , snake_case__ : int = 16 ): """simple docstring""" _snake_case : Optional[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _snake_case : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(snake_case__ : Any ): # max_length=None => use the model max length (it's actually the default) _snake_case : Any = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _snake_case : List[Any] = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case : int = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _snake_case : Optional[int] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _snake_case : str = 16 elif accelerator.mixed_precision != "no": _snake_case : Optional[int] = 8 else: _snake_case : Optional[int] = None return tokenizer.pad( snake_case__ , padding="""longest""" , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _snake_case : Optional[int] = DataLoader( tokenized_datasets["""train"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) _snake_case : Dict = DataLoader( tokenized_datasets["""validation"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders A_ = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any ): """simple docstring""" if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , snake_case__ ) == "1": _snake_case : List[Any] = 2 # Initialize accelerator _snake_case : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case : Tuple = config["""lr"""] _snake_case : str = int(config["""num_epochs"""] ) _snake_case : Union[str, Any] = int(config["""seed"""] ) _snake_case : Union[str, Any] = int(config["""batch_size"""] ) _snake_case : List[str] = evaluate.load("""glue""" , """mrpc""" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case__ ) def inner_training_loop(snake_case__ : Union[str, Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case : List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _snake_case : Tuple = model.to(accelerator.device ) # Instantiate optimizer _snake_case : str = AdamW(params=model.parameters() , lr=snake_case__ ) _snake_case , _snake_case : Optional[int] = get_dataloaders(snake_case__ , snake_case__ ) # Instantiate scheduler _snake_case : str = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=1_00 , num_training_steps=(len(snake_case__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : List[str] = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _snake_case : int = model(**snake_case__ ) _snake_case : str = outputs.loss accelerator.backward(snake_case__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _snake_case : int = model(**snake_case__ ) _snake_case : Optional[Any] = outputs.logits.argmax(dim=-1 ) _snake_case , _snake_case : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) _snake_case : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , snake_case__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=snake_case__ , default=snake_case__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _snake_case : Dict = parser.parse_args() _snake_case : int = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
64
0
'''simple docstring''' import math class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : List[Any]=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' lowercase__ = n lowercase__ = [ [math.inf for j in range(0 , UpperCamelCase )] for i in range(0 , UpperCamelCase ) ] # adjacency matrix for weight lowercase__ = [ [math.inf for j in range(0 , UpperCamelCase )] for i in range(0 , UpperCamelCase ) ] # dp[i][j] stores minimum distance from i to j def UpperCamelCase__ (self : Any , UpperCamelCase : int , UpperCamelCase : Optional[int] , UpperCamelCase : List[Any] ): '''simple docstring''' lowercase__ = w def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): lowercase__ = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def UpperCamelCase__ (self : Any , UpperCamelCase : int , UpperCamelCase : int ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": lowerCamelCase : Any = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
2
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def UpperCAmelCase__ (snake_case__ : Optional[int] , snake_case__ : Any=7 ): """simple docstring""" _snake_case : Any = None if token is not None: _snake_case : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} # The id of a workflow (not of a workflow run) _snake_case : List[str] = """636036""" _snake_case : Union[str, Any] = F"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}" _snake_case : str = requests.get(snake_case__ , headers=snake_case__ ).json() return result["workflow_runs"] def UpperCAmelCase__ (snake_case__ : Optional[Any] ): """simple docstring""" _snake_case : str = get_daily_ci_runs(snake_case__ ) _snake_case : str = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _snake_case : List[str] = workflow_run["""id"""] break return workflow_run_id def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Union[str, Any] , snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Optional[Any] = get_last_daily_ci_runs(snake_case__ ) if workflow_run_id is not None: _snake_case : Optional[Any] = get_artifacts_links(worflow_run_id=snake_case__ , token=snake_case__ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _snake_case : Optional[int] = artifacts_links[artifact_name] download_artifact( artifact_name=snake_case__ , artifact_url=snake_case__ , output_dir=snake_case__ , token=snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] , snake_case__ : List[str] , snake_case__ : int ): """simple docstring""" get_last_daily_ci_artifacts(snake_case__ , snake_case__ , snake_case__ ) _snake_case : int = {} for artifact_name in artifact_names: _snake_case : int = os.path.join(snake_case__ , F"{artifact_name}.zip" ) if os.path.isfile(snake_case__ ): _snake_case : Tuple = {} with zipfile.ZipFile(snake_case__ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case__ ): # read the file with z.open(snake_case__ ) as f: _snake_case : Any = f.read().decode("""UTF-8""" ) return results
64
0
'''simple docstring''' 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, ) lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase : str = '\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 lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__=8 ): '''simple docstring''' A : int = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 A : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def lowerCAmelCase_ ( snake_case__ , snake_case__=512 , snake_case__=512 ): '''simple docstring''' A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) A : str = np.array(pil_image.convert('''RGB''' ) ) A : Union[str, Any] = arr.astype(np.floataa ) / 1_27.5 - 1 A : Tuple = np.transpose(snake_case__ , [2, 0, 1] ) A : List[str] = torch.from_numpy(snake_case__ ).unsqueeze(0 ) return image class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__() self.register_modules( unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , movq=SCREAMING_SNAKE_CASE , ) A : Dict = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : Any = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE ) A : int = max(num_inference_steps - init_timestep , 0 ) A : str = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None ) -> List[Any]: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , (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(SCREAMING_SNAKE_CASE )}' ) A : str = image.to(device=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: A : Optional[int] = image else: if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Union[str, Any] = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE ) ] A : Optional[int] = torch.cat(SCREAMING_SNAKE_CASE , dim=0 ) else: A : Optional[Any] = self.movq.encode(SCREAMING_SNAKE_CASE ).latent_dist.sample(SCREAMING_SNAKE_CASE ) A : str = self.movq.config.scaling_factor * init_latents A : Any = torch.cat([init_latents] , dim=0 ) A : Tuple = init_latents.shape A : str = randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE ) # get latents A : str = self.scheduler.add_noise(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Dict = init_latents return latents def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 ) -> List[Any]: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) A : List[Any] = torch.device(F'cuda:{gpu_id}' ) A : Optional[int] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 ) -> Tuple: """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 : Dict = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) A : Union[str, Any] = None for cpu_offloaded_model in [self.unet, self.movq]: A, A : str = cpu_offload_with_hook(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , prev_module_hook=SCREAMING_SNAKE_CASE ) # We'll offload the last model manually. A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(SCREAMING_SNAKE_CASE , '''_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(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 512 , SCREAMING_SNAKE_CASE = 512 , SCREAMING_SNAKE_CASE = 100 , SCREAMING_SNAKE_CASE = 4.0 , SCREAMING_SNAKE_CASE = 0.3 , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , ) -> List[str]: """simple docstring""" A : Tuple = self._execution_device A : Any = guidance_scale > 1.0 if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : str = torch.cat(SCREAMING_SNAKE_CASE , dim=0 ) A : str = image_embeds.shape[0] if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Dict = torch.cat(SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: A : Union[str, Any] = image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE , dim=0 ) A : List[str] = negative_image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE , dim=0 ) A : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=SCREAMING_SNAKE_CASE ) if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Dict = [image] if not all(isinstance(SCREAMING_SNAKE_CASE , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F'Input is in incorrect format: {[type(SCREAMING_SNAKE_CASE ) for i in image]}. Currently, we only support PIL image and pytorch tensor' ) A : Tuple = torch.cat([prepare_image(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for i in image] , dim=0 ) A : Tuple = image.to(dtype=image_embeds.dtype , device=SCREAMING_SNAKE_CASE ) A : Tuple = self.movq.encode(SCREAMING_SNAKE_CASE )['''latents'''] A : int = latents.repeat_interleave(SCREAMING_SNAKE_CASE , dim=0 ) self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE , device=SCREAMING_SNAKE_CASE ) A, A : Optional[int] = self.get_timesteps(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Any = timesteps[:1].repeat(batch_size * num_images_per_prompt ) A, A : Optional[Any] = downscale_height_and_width(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.movq_scale_factor ) A : Optional[int] = self.prepare_latents( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , image_embeds.dtype , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance A : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A : Dict = {'''image_embeds''': image_embeds} A : Tuple = self.unet( sample=SCREAMING_SNAKE_CASE , timestep=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , added_cond_kwargs=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , )[0] if do_classifier_free_guidance: A, A : List[str] = noise_pred.split(latents.shape[1] , dim=1 ) A, A : List[str] = noise_pred.chunk(2 ) A, A : Tuple = variance_pred.chunk(2 ) A : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) A : Any = 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 : List[str] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 A : List[Any] = self.scheduler.step( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , )[0] # post-processing A : Tuple = self.movq.decode(SCREAMING_SNAKE_CASE , force_not_quantize=SCREAMING_SNAKE_CASE )['''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 : Union[str, Any] = image * 0.5 + 0.5 A : Dict = image.clamp(0 , 1 ) A : Any = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": A : int = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE )
3
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging A_ = logging.get_logger(__name__) class lowercase: '''simple docstring''' lowercase__ = 42 lowercase__ = None @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Tuple, a_: int, a_: int, a_: str, **a_: Dict ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any], a_: List[str] ): '''simple docstring''' raise NotImplementedError def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.is_available(): raise RuntimeError( f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}." ) @classmethod def UpperCamelCase_ ( cls: Tuple ): '''simple docstring''' return f"`pip install {cls.pip_package or cls.name}`" class lowercase( __a ): '''simple docstring''' lowercase__ = "optuna" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def UpperCamelCase_ ( self: Union[str, Any], a_: List[Any], a_: int, a_: str, **a_: List[str] ): '''simple docstring''' return run_hp_search_optuna(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], a_: Any ): '''simple docstring''' return default_hp_space_optuna(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "ray" lowercase__ = "'ray[tune]'" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_ray_available() def UpperCamelCase_ ( self: int, a_: Optional[Any], a_: int, a_: str, **a_: List[Any] ): '''simple docstring''' return run_hp_search_ray(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Tuple ): '''simple docstring''' return default_hp_space_ray(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "sigopt" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def UpperCamelCase_ ( self: Dict, a_: str, a_: int, a_: str, **a_: int ): '''simple docstring''' return run_hp_search_sigopt(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: List[str] ): '''simple docstring''' return default_hp_space_sigopt(a_ ) class lowercase( __a ): '''simple docstring''' lowercase__ = "wandb" @staticmethod def UpperCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def UpperCamelCase_ ( self: Optional[Any], a_: str, a_: int, a_: str, **a_: Union[str, Any] ): '''simple docstring''' return run_hp_search_wandb(a_, a_, a_, **a_ ) def UpperCamelCase_ ( self: str, a_: Any ): '''simple docstring''' return default_hp_space_wandb(a_ ) A_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def UpperCAmelCase__ (): """simple docstring""" _snake_case : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(snake_case__ ) > 0: _snake_case : Any = available_backends[0].name if len(snake_case__ ) > 1: logger.info( F"{len(snake_case__ )} hyperparameter search backends available. Using {name} as the default." ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( F" - To install {backend.name} run {backend.pip_install()}" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
64
0
'''simple docstring''' import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class UpperCAmelCase_ ( nn.Module ): def __init__( self : Dict ) -> List[str]: super().__init__() lowerCAmelCase = nn.Linear(3 , 4 ) lowerCAmelCase = nn.BatchNormad(4 ) lowerCAmelCase = nn.Linear(4 , 5 ) def __UpperCAmelCase ( self : List[Any] , UpperCAmelCase__ : Tuple ) -> Any: return self.lineara(self.batchnorm(self.lineara(UpperCAmelCase__ ) ) ) class UpperCAmelCase_ ( unittest.TestCase ): def __UpperCAmelCase ( self : Any ) -> Any: lowerCAmelCase = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCAmelCase__ , model.state_dict() ) lowerCAmelCase = os.path.join(UpperCAmelCase__ , 'index.json' ) self.assertTrue(os.path.isfile(UpperCAmelCase__ ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: lowerCAmelCase = os.path.join(UpperCAmelCase__ , F'''{key}.dat''' ) self.assertTrue(os.path.isfile(UpperCAmelCase__ ) ) # TODO: add tests on the fact weights are properly loaded def __UpperCAmelCase ( self : Optional[Any] ) -> Tuple: lowerCAmelCase = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: lowerCAmelCase = torch.randn(2 , 3 , dtype=UpperCAmelCase__ ) with TemporaryDirectory() as tmp_dir: lowerCAmelCase = offload_weight(UpperCAmelCase__ , 'weight' , UpperCAmelCase__ , {} ) lowerCAmelCase = os.path.join(UpperCAmelCase__ , 'weight.dat' ) self.assertTrue(os.path.isfile(UpperCAmelCase__ ) ) self.assertDictEqual(UpperCAmelCase__ , {'weight': {'shape': [2, 3], 'dtype': str(UpperCAmelCase__ ).split('.' )[1]}} ) lowerCAmelCase = load_offloaded_weight(UpperCAmelCase__ , index['weight'] ) self.assertTrue(torch.equal(UpperCAmelCase__ , UpperCAmelCase__ ) ) def __UpperCAmelCase ( self : Tuple ) -> Any: lowerCAmelCase = ModelForTest() lowerCAmelCase = model.state_dict() lowerCAmelCase = {k: v for k, v in state_dict.items() if 'linear2' not in k} lowerCAmelCase = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = OffloadedWeightsLoader(state_dict=UpperCAmelCase__ , save_folder=UpperCAmelCase__ ) # Every key is there with the right value self.assertEqual(sorted(UpperCAmelCase__ ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCAmelCase__ , weight_map[key] ) ) lowerCAmelCase = {k: v for k, v in state_dict.items() if 'weight' in k} lowerCAmelCase = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = OffloadedWeightsLoader(state_dict=UpperCAmelCase__ , save_folder=UpperCAmelCase__ ) # Every key is there with the right value self.assertEqual(sorted(UpperCAmelCase__ ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCAmelCase__ , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCAmelCase__ , UpperCAmelCase__ ) # Duplicates are removed lowerCAmelCase = OffloadedWeightsLoader(state_dict=UpperCAmelCase__ , save_folder=UpperCAmelCase__ ) # Every key is there with the right value self.assertEqual(sorted(UpperCAmelCase__ ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCAmelCase__ , weight_map[key] ) ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: lowerCAmelCase = {'a.1': 0, 'a.10': 1, 'a.2': 2} lowerCAmelCase = extract_submodules_state_dict(UpperCAmelCase__ , ['a.1', 'a.2'] ) self.assertDictEqual(UpperCAmelCase__ , {'a.1': 0, 'a.2': 2} ) lowerCAmelCase = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} lowerCAmelCase = extract_submodules_state_dict(UpperCAmelCase__ , ['a.1', 'a.2'] ) self.assertDictEqual(UpperCAmelCase__ , {'a.1.a': 0, 'a.2.a': 2} )
4
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowercase( __a ): '''simple docstring''' lowercase__ = ["image_processor", "tokenizer"] lowercase__ = "AutoImageProcessor" lowercase__ = "AutoTokenizer" def __init__( self: List[str], a_: List[str]=None, a_: Tuple=None, **a_: Tuple ): '''simple docstring''' _snake_case : str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""", a_, ) _snake_case : str = kwargs.pop("""feature_extractor""" ) _snake_case : Union[str, Any] = 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__(a_, a_ ) _snake_case : Dict = self.image_processor _snake_case : Any = False def __call__( self: Any, *a_: Any, **a_: Tuple ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*a_, **a_ ) _snake_case : Dict = kwargs.pop("""images""", a_ ) _snake_case : Optional[Any] = kwargs.pop("""text""", a_ ) if len(a_ ) > 0: _snake_case : Optional[int] = args[0] _snake_case : Tuple = args[1:] if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: _snake_case : Tuple = self.image_processor(a_, *a_, **a_ ) if text is not None: _snake_case : Tuple = self.tokenizer(a_, **a_ ) if text is None: return inputs elif images is None: return encodings else: _snake_case : List[str] = encodings["""input_ids"""] return inputs def UpperCamelCase_ ( self: Optional[int], *a_: Tuple, **a_: List[str] ): '''simple docstring''' return self.tokenizer.batch_decode(*a_, **a_ ) def UpperCamelCase_ ( self: int, *a_: List[str], **a_: int ): '''simple docstring''' return self.tokenizer.decode(*a_, **a_ ) @contextmanager def UpperCamelCase_ ( self: Dict ): '''simple docstring''' warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your images inputs, or in a separate call.""" ) _snake_case : Any = True _snake_case : Optional[int] = self.tokenizer yield _snake_case : int = self.image_processor _snake_case : Optional[int] = False def UpperCamelCase_ ( self: Dict, a_: Optional[Any], a_: str=False, a_: Optional[Any]=None ): '''simple docstring''' if added_vocab is None: _snake_case : Dict = self.tokenizer.get_added_vocab() _snake_case : str = {} while tokens: _snake_case : Union[str, Any] = re.search(r"""<s_(.*?)>""", a_, re.IGNORECASE ) if start_token is None: break _snake_case : List[Any] = start_token.group(1 ) _snake_case : str = re.search(rf"</s_{key}>", a_, re.IGNORECASE ) _snake_case : Dict = start_token.group() if end_token is None: _snake_case : List[Any] = tokens.replace(a_, """""" ) else: _snake_case : List[str] = end_token.group() _snake_case : str = re.escape(a_ ) _snake_case : str = re.escape(a_ ) _snake_case : Union[str, Any] = re.search(f"{start_token_escaped}(.*?){end_token_escaped}", a_, re.IGNORECASE ) if content is not None: _snake_case : int = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node _snake_case : List[Any] = self.tokenajson(a_, is_inner_value=a_, added_vocab=a_ ) if value: if len(a_ ) == 1: _snake_case : List[str] = value[0] _snake_case : List[str] = value else: # leaf nodes _snake_case : Tuple = [] for leaf in content.split(r"""<sep/>""" ): _snake_case : Tuple = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": _snake_case : int = leaf[1:-2] # for categorical special tokens output[key].append(a_ ) if len(output[key] ) == 1: _snake_case : int = output[key][0] _snake_case : Any = tokens[tokens.find(a_ ) + len(a_ ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:], is_inner_value=a_, added_vocab=a_ ) if len(a_ ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""", a_, ) return self.image_processor_class @property def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""", a_, ) return self.image_processor
64
0
import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType UpperCAmelCase__ = logging.get_logger(__name__) class lowerCamelCase__ ( lowerCAmelCase): SCREAMING_SNAKE_CASE__ = '''vision-encoder-decoder''' SCREAMING_SNAKE_CASE__ = True def __init__(self , **UpperCAmelCase ) -> str: super().__init__(**UpperCAmelCase ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( f"A configuraton of type {self.model_type} cannot be instantiated because " f"not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}" ) _lowercase =kwargs.pop('''encoder''' ) _lowercase =encoder_config.pop('''model_type''' ) _lowercase =kwargs.pop('''decoder''' ) _lowercase =decoder_config.pop('''model_type''' ) _lowercase =AutoConfig.for_model(UpperCAmelCase , **UpperCAmelCase ) _lowercase =AutoConfig.for_model(UpperCAmelCase , **UpperCAmelCase ) _lowercase =True @classmethod def __A (cls , UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase ) -> PretrainedConfig: logger.info('''Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) _lowercase =True _lowercase =True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **UpperCAmelCase ) def __A (self ) -> Optional[Any]: _lowercase =copy.deepcopy(self.__dict__ ) _lowercase =self.encoder.to_dict() _lowercase =self.decoder.to_dict() _lowercase =self.__class__.model_type return output class lowerCamelCase__ ( lowerCAmelCase): SCREAMING_SNAKE_CASE__ = version.parse('''1.11''') @property def __A (self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __A (self ) -> float: return 1e-4 @property def __A (self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict({'''last_hidden_state''': {0: '''batch''', 1: '''encoder_sequence'''}} ) class lowerCamelCase__ ( lowerCAmelCase): @property def __A (self ) -> Mapping[str, Mapping[int, str]]: _lowercase =OrderedDict() _lowercase ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''} _lowercase ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''} _lowercase ={0: '''batch''', 1: '''encoder_sequence'''} return common_inputs def __A (self , UpperCAmelCase , UpperCAmelCase = -1 , UpperCAmelCase = -1 , UpperCAmelCase = False , UpperCAmelCase = None , ) -> Mapping[str, Any]: import torch _lowercase =OrderedDict() _lowercase =super().generate_dummy_inputs( UpperCAmelCase , batch_size=UpperCAmelCase , seq_length=UpperCAmelCase , is_pair=UpperCAmelCase , framework=UpperCAmelCase ) _lowercase , _lowercase =dummy_input['''input_ids'''].shape _lowercase =(batch, encoder_sequence, self._config.encoder_hidden_size) _lowercase =dummy_input.pop('''input_ids''' ) _lowercase =dummy_input.pop('''attention_mask''' ) _lowercase =torch.zeros(UpperCAmelCase ) return common_inputs class lowerCamelCase__ ( lowerCAmelCase): @property def __A (self ) -> None: pass def __A (self , UpperCAmelCase ) -> OnnxConfig: return VisionEncoderDecoderEncoderOnnxConfig(UpperCAmelCase ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = "default" ) -> OnnxConfig: _lowercase =encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(UpperCAmelCase , UpperCAmelCase )
5
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : int = 0.00 _snake_case : int = 0 for resistor in resistors: if resistor <= 0: _snake_case : Dict = F"Resistor at index {index} has a negative or zero value!" raise ValueError(snake_case__ ) first_sum += 1 / float(snake_case__ ) index += 1 return 1 / first_sum def UpperCAmelCase__ (snake_case__ : list[float] ): """simple docstring""" _snake_case : Union[str, Any] = 0.00 _snake_case : Any = 0 for resistor in resistors: sum_r += resistor if resistor < 0: _snake_case : Any = F"Resistor at index {index} has a negative value!" raise ValueError(snake_case__ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
64
0
def __lowerCAmelCase ( a__ , a__ , a__ ) -> int: def count_of_possible_combinations(a__ ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(a__ ) def __lowerCAmelCase ( a__ , a__ , a__ ) -> int: def count_of_possible_combinations_with_dp_array( a__ , a__ ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] __a = sum( count_of_possible_combinations_with_dp_array(target - item , a__ ) for item in array ) __a = answer return answer __a = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(a__ , a__ ) def __lowerCAmelCase ( a__ , a__ , a__ ) -> int: __a = [0] * (target + 1) __a = 1 for i in range(1 , target + 1 ): for j in range(a__ ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() A : Dict = 3 A : Any = 5 A : Tuple = [1, 2, 5] print(combination_sum_iv(n, array, target))
6
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''', }, '''merges_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''Salesforce/codegen-350M-mono''': ( '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json''' ), }, } A_ = { '''Salesforce/codegen-350M-mono''': 20_48, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] lowercase__ = CodeGenTokenizer def __init__( self: Union[str, Any], a_: List[Any]=None, a_: str=None, a_: str=None, a_: Dict="<|endoftext|>", a_: Tuple="<|endoftext|>", a_: str="<|endoftext|>", a_: List[Any]=False, **a_: List[str], ): '''simple docstring''' super().__init__( a_, a_, tokenizer_file=a_, unk_token=a_, bos_token=a_, eos_token=a_, add_prefix_space=a_, **a_, ) if kwargs.pop("""add_bos_token""", a_ ): _snake_case : str = kwargs.pop("""name_or_path""", """""" ) raise ValueError( """Currenty GPT2's fast tokenizer does NOT support adding a BOS token.""" """Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n""" f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n" f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n" """This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.""" """ so that the fast tokenizer works correctly.""" ) _snake_case : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : Dict = getattr(a_, pre_tok_state.pop("""type""" ) ) _snake_case : Dict = add_prefix_space _snake_case : str = pre_tok_class(**a_ ) _snake_case : List[Any] = add_prefix_space def UpperCamelCase_ ( self: Any, *a_: Any, **a_: int ): '''simple docstring''' _snake_case : Optional[int] = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], *a_: Any, **a_: List[str] ): '''simple docstring''' _snake_case : Dict = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : List[Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ ) def UpperCamelCase_ ( self: str, a_: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], a_: bool = False, a_: bool = None, a_: Optional[List[str]] = None, **a_: List[str], ): '''simple docstring''' _snake_case : Any = super().decode( token_ids=a_, skip_special_tokens=a_, clean_up_tokenization_spaces=a_, **a_, ) if truncate_before_pattern is not None and len(a_ ) > 0: _snake_case : List[str] = self.truncate(a_, a_ ) return decoded_text def UpperCamelCase_ ( self: Dict, a_: Tuple, a_: Optional[Any] ): '''simple docstring''' def find_re(a_: Dict, a_: str, a_: Union[str, Any] ): _snake_case : Any = pattern.search(a_, a_ ) return m.start() if m else -1 _snake_case : Tuple = [re.compile(a_, re.MULTILINE ) for pattern in truncate_before_pattern] _snake_case : List[Any] = list(re.finditer("""^print""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : int = completion[: prints[1].start()] _snake_case : List[str] = list(re.finditer("""^def""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : List[Any] = completion[: defs[1].start()] _snake_case : int = 0 _snake_case : List[Any] = [ pos for pos in [find_re(a_, a_, a_ ) for terminal in terminals] if pos != -1 ] if len(a_ ) > 0: return completion[: min(a_ )] else: return completion
64
0
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class A : """simple docstring""" def __init__( self : Union[str, Any],lowercase_ : int,lowercase_ : List[Any]=3,lowercase_ : Dict=3_2,lowercase_ : List[str]=3,lowercase_ : List[str]=1_0,lowercase_ : List[Any]=[8, 1_6, 3_2, 6_4],lowercase_ : Any=[1, 1, 2, 1],lowercase_ : Any=True,lowercase_ : List[Any]=True,lowercase_ : Union[str, Any]="relu",lowercase_ : int=3,lowercase_ : Tuple=None,lowercase_ : Union[str, Any]=["stage2", "stage3", "stage4"],lowercase_ : Tuple=[2, 3, 4],lowercase_ : List[Any]=1,)-> int: '''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(lowercase_ ) A__ = out_features A__ = out_indices A__ = num_groups def snake_case__ ( self : Any )-> Optional[Any]: '''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.num_labels ) A__ = self.get_config() return config, pixel_values, labels def snake_case__ ( self : List[str] )-> Tuple: '''simple docstring''' return BitConfig( 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,out_features=self.out_features,out_indices=self.out_indices,num_groups=self.num_groups,) def snake_case__ ( self : Dict,lowercase_ : int,lowercase_ : Optional[int],lowercase_ : Optional[Any] )-> Dict: '''simple docstring''' A__ = BitModel(config=lowercase_ ) model.to(lowercase_ ) model.eval() A__ = model(lowercase_ ) self.parent.assertEqual( result.last_hidden_state.shape,(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2),) def snake_case__ ( self : Union[str, Any],lowercase_ : List[Any],lowercase_ : Tuple,lowercase_ : Tuple )-> Optional[int]: '''simple docstring''' A__ = self.num_labels A__ = BitForImageClassification(lowercase_ ) model.to(lowercase_ ) model.eval() A__ = model(lowercase_,labels=lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels) ) def snake_case__ ( self : int,lowercase_ : str,lowercase_ : Dict,lowercase_ : List[str] )-> Union[str, Any]: '''simple docstring''' A__ = BitBackbone(config=lowercase_ ) model.to(lowercase_ ) model.eval() A__ = model(lowercase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ),len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ),[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ),len(config.out_features ) ) self.parent.assertListEqual(model.channels,config.hidden_sizes[1:] ) # verify backbone works with out_features=None A__ = None A__ = BitBackbone(config=lowercase_ ) model.to(lowercase_ ) model.eval() A__ = model(lowercase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ),1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ),[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ),1 ) self.parent.assertListEqual(model.channels,[config.hidden_sizes[-1]] ) def snake_case__ ( self : Tuple )-> Optional[int]: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ = config_and_inputs A__ = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () lowerCamelCase = ( {'feature-extraction': BitModel, 'image-classification': BitForImageClassification} if is_torch_available() else {} ) lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def snake_case__ ( self : Union[str, Any] )-> int: '''simple docstring''' A__ = BitModelTester(self ) A__ = ConfigTester(self,config_class=lowercase_,has_text_modality=lowercase_ ) def snake_case__ ( self : Dict )-> 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 snake_case__ ( self : Union[str, Any] )-> Tuple: '''simple docstring''' return @unittest.skip(reason='Bit does not output attentions' ) def snake_case__ ( self : Tuple )-> Tuple: '''simple docstring''' pass @unittest.skip(reason='Bit does not use inputs_embeds' ) def snake_case__ ( self : Dict )-> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason='Bit does not support input and output embeddings' ) def snake_case__ ( self : Optional[Any] )-> Optional[Any]: '''simple docstring''' pass def snake_case__ ( self : List[str] )-> 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(lowercase_ ) 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],lowercase_ ) def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def snake_case__ ( self : List[str] )-> Optional[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowercase_ ) def snake_case__ ( self : Any )-> 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(config=lowercase_ ) for name, module in model.named_modules(): if isinstance(lowercase_,(nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ),msg=F'Parameter {name} of model {model_class} seems not properly initialized',) self.assertTrue( torch.all(module.bias == 0 ),msg=F'Parameter {name} of model {model_class} seems not properly initialized',) def snake_case__ ( self : Dict )-> Tuple: '''simple docstring''' def check_hidden_states_output(lowercase_ : Any,lowercase_ : Union[str, Any],lowercase_ : Dict ): A__ = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(lowercase_,lowercase_ ) ) A__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states A__ = self.model_tester.num_stages self.assertEqual(len(lowercase_ ),expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ),[self.model_tester.image_size // 4, self.model_tester.image_size // 4],) A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = ['preactivation', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: A__ = layer_type A__ = True check_hidden_states_output(lowercase_,lowercase_,lowercase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ = True check_hidden_states_output(lowercase_,lowercase_,lowercase_ ) @unittest.skip(reason='Bit does not use feedforward chunking' ) def snake_case__ ( self : int )-> str: '''simple docstring''' pass def snake_case__ ( self : Any )-> Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def snake_case__ ( self : str )-> str: '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = BitModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def _snake_case( ) -> str: '''simple docstring''' A__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class A ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case__ ( self : Tuple )-> Optional[int]: '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def snake_case__ ( self : Optional[int] )-> Dict: '''simple docstring''' A__ = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(lowercase_ ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(images=lowercase_,return_tensors='pt' ).to(lowercase_ ) # forward pass with torch.no_grad(): A__ = model(**lowercase_ ) # verify the logits A__ = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape,lowercase_ ) A__ = torch.tensor([[-0.6_526, -0.5_263, -1.4_398]] ).to(lowercase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3],lowercase_,atol=1E-4 ) ) @require_torch class A ( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = (BitBackbone,) if is_torch_available() else () lowerCamelCase = BitConfig lowerCamelCase = False def snake_case__ ( self : Tuple )-> Optional[int]: '''simple docstring''' A__ = BitModelTester(self )
7
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : List[Any] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _snake_case : Tuple = 1_92 _snake_case : Any = 7_68 _snake_case : Any = 12 _snake_case : List[Any] = 3 _snake_case : int = [8_00, 13_33] _snake_case : Tuple = False elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = 3_30 _snake_case : List[str] = 14 _snake_case : List[str] = 6 _snake_case : Union[str, Any] = 13_20 elif "yolos_s" in yolos_name: _snake_case : Union[str, Any] = 3_84 _snake_case : List[str] = 15_36 _snake_case : Any = 12 _snake_case : Optional[int] = 6 elif "yolos_b" in yolos_name: _snake_case : Dict = [8_00, 13_44] _snake_case : str = 91 _snake_case : Optional[Any] = """huggingface/label-files""" _snake_case : str = """coco-detection-id2label.json""" _snake_case : str = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="""dataset""" ) , """r""" ) ) _snake_case : Union[str, Any] = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[str] = idalabel _snake_case : List[str] = {v: k for k, v in idalabel.items()} return config def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosConfig , snake_case__ : bool = False ): """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : int = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) _snake_case : Union[str, Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Any = in_proj_weight[: config.hidden_size, :] _snake_case : Optional[Any] = in_proj_bias[: config.hidden_size] _snake_case : Optional[int] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Tuple = in_proj_weight[-config.hidden_size :, :] _snake_case : List[Any] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" if "backbone" in name: _snake_case : str = name.replace("""backbone""" , """vit""" ) if "cls_token" in name: _snake_case : Union[str, Any] = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "det_token" in name: _snake_case : str = name.replace("""det_token""" , """embeddings.detection_tokens""" ) if "mid_pos_embed" in name: _snake_case : str = name.replace("""mid_pos_embed""" , """encoder.mid_position_embeddings""" ) if "pos_embed" in name: _snake_case : Tuple = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: _snake_case : str = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "blocks" in name: _snake_case : str = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: _snake_case : Any = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: _snake_case : str = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: _snake_case : List[str] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: _snake_case : str = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: _snake_case : List[str] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: _snake_case : int = name.replace("""mlp.fc2""" , """output.dense""" ) if "class_embed" in name: _snake_case : Union[str, Any] = name.replace("""class_embed""" , """class_labels_classifier""" ) if "bbox_embed" in name: _snake_case : str = name.replace("""bbox_embed""" , """bbox_predictor""" ) if "vit.norm" in name: _snake_case : Union[str, Any] = name.replace("""vit.norm""" , """vit.layernorm""" ) return name def UpperCAmelCase__ (snake_case__ : dict , snake_case__ : YolosForObjectDetection ): """simple docstring""" for key in orig_state_dict.copy().keys(): _snake_case : List[str] = orig_state_dict.pop(snake_case__ ) if "qkv" in key: _snake_case : Optional[Any] = key.split(""".""" ) _snake_case : Optional[Any] = int(key_split[2] ) _snake_case : Optional[int] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _snake_case : str = val[:dim, :] _snake_case : Optional[Any] = val[ dim : dim * 2, : ] _snake_case : Optional[Any] = val[-dim:, :] else: _snake_case : Dict = val[:dim] _snake_case : Any = val[dim : dim * 2] _snake_case : Dict = val[-dim:] else: _snake_case : Tuple = val return orig_state_dict def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Union[str, Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : str , snake_case__ : bool = False ): """simple docstring""" _snake_case : Optional[Any] = get_yolos_config(snake_case__ ) # load original state_dict _snake_case : Optional[int] = torch.load(snake_case__ , map_location="""cpu""" )["""model"""] # load 🤗 model _snake_case : Optional[Any] = YolosForObjectDetection(snake_case__ ) model.eval() _snake_case : Optional[Any] = convert_state_dict(snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ ) # Check outputs on an image, prepared by YolosImageProcessor _snake_case : List[str] = 8_00 if yolos_name != """yolos_ti""" else 5_12 _snake_case : Optional[int] = YolosImageProcessor(format="""coco_detection""" , size=snake_case__ ) _snake_case : Optional[Any] = image_processor(images=prepare_img() , return_tensors="""pt""" ) _snake_case : Optional[Any] = model(**snake_case__ ) _snake_case , _snake_case : Optional[int] = outputs.logits, outputs.pred_boxes _snake_case , _snake_case : Dict = None, None if yolos_name == "yolos_ti": _snake_case : Optional[Any] = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) _snake_case : Tuple = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": _snake_case : List[str] = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) _snake_case : List[str] = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": _snake_case : Dict = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) _snake_case : Union[str, Any] = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": _snake_case : Tuple = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) _snake_case : Optional[Any] = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": _snake_case : int = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) _snake_case : Optional[int] = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(F"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , snake_case__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , snake_case__ , atol=1e-4 ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if push_to_hub: _snake_case : Dict = { """yolos_ti""": """yolos-tiny""", """yolos_s_200_pre""": """yolos-small""", """yolos_s_300_pre""": """yolos-small-300""", """yolos_s_dWr""": """yolos-small-dwr""", """yolos_base""": """yolos-base""", } print("""Pushing to the hub...""" ) _snake_case : str = model_mapping[yolos_name] image_processor.push_to_hub(snake_case__ , organization="""hustvl""" ) model.push_to_hub(snake_case__ , organization="""hustvl""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.pth file).''' ) 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.''' ) A_ = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
64
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCAmelCase_ = { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/config.json''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/config.json''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/config.json''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/config.json''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/config.json''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json''', } class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = "albert" def __init__( self : Tuple , _UpperCamelCase : List[str]=3_0_0_0_0 , _UpperCamelCase : Optional[Any]=1_2_8 , _UpperCamelCase : List[Any]=4_0_9_6 , _UpperCamelCase : int=1_2 , _UpperCamelCase : Union[str, Any]=1 , _UpperCamelCase : Any=6_4 , _UpperCamelCase : str=1_6_3_8_4 , _UpperCamelCase : str=1 , _UpperCamelCase : Union[str, Any]="gelu_new" , _UpperCamelCase : Union[str, Any]=0 , _UpperCamelCase : Union[str, Any]=0 , _UpperCamelCase : Optional[Any]=5_1_2 , _UpperCamelCase : Any=2 , _UpperCamelCase : List[str]=0.02 , _UpperCamelCase : Dict=1e-12 , _UpperCamelCase : Tuple=0.1 , _UpperCamelCase : Tuple="absolute" , _UpperCamelCase : int=0 , _UpperCamelCase : int=2 , _UpperCamelCase : Any=3 , **_UpperCamelCase : Dict , ) ->Dict: super().__init__(pad_token_id=_UpperCamelCase , bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase , **_UpperCamelCase ) snake_case_ = vocab_size snake_case_ = embedding_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_hidden_groups snake_case_ = num_attention_heads snake_case_ = inner_group_num snake_case_ = hidden_act snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = classifier_dropout_prob snake_case_ = position_embedding_type class snake_case_ ( __A ): '''simple docstring''' @property def snake_case__( self : Optional[int] ) ->Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": snake_case_ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: snake_case_ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
8
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str]=False ): """simple docstring""" _snake_case : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"module.blocks.{i}.norm1.weight", F"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((F"module.blocks.{i}.norm1.bias", F"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (F"module.blocks.{i}.attn.proj.weight", F"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.attn.proj.bias", F"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((F"module.blocks.{i}.norm2.weight", F"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((F"module.blocks.{i}.norm2.bias", F"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.weight", F"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc1.bias", F"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.weight", F"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((F"module.blocks.{i}.mlp.fc2.bias", F"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _snake_case : Any = [(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 UpperCAmelCase__ (snake_case__ : Dict , snake_case__ : Dict , snake_case__ : List[str]=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _snake_case : List[Any] = """""" else: _snake_case : List[Any] = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.weight" ) _snake_case : Optional[Any] = state_dict.pop(F"module.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _snake_case : Optional[Any] = in_proj_weight[ : config.hidden_size, : ] _snake_case : Union[str, Any] = in_proj_bias[: config.hidden_size] _snake_case : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case : Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] _snake_case : List[str] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase__ (snake_case__ : str ): """simple docstring""" _snake_case : Tuple = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" _snake_case : List[str] = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : int ): """simple docstring""" _snake_case : Optional[Any] = dct.pop(snake_case__ ) _snake_case : Union[str, Any] = val def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : str ): """simple docstring""" _snake_case : str = ViTMSNConfig() _snake_case : Any = 10_00 _snake_case : Tuple = """datasets/huggingface/label-files""" _snake_case : Dict = """imagenet-1k-id2label.json""" _snake_case : int = json.load(open(hf_hub_download(snake_case__ , snake_case__ ) , """r""" ) ) _snake_case : Any = {int(snake_case__ ): v for k, v in idalabel.items()} _snake_case : List[Any] = idalabel _snake_case : str = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: _snake_case : Tuple = 3_84 _snake_case : Dict = 15_36 _snake_case : Tuple = 6 elif "l16" in checkpoint_url: _snake_case : Any = 10_24 _snake_case : int = 40_96 _snake_case : str = 24 _snake_case : Optional[int] = 16 _snake_case : List[Any] = 0.1 elif "b4" in checkpoint_url: _snake_case : Tuple = 4 elif "l7" in checkpoint_url: _snake_case : int = 7 _snake_case : Dict = 10_24 _snake_case : Optional[Any] = 40_96 _snake_case : Any = 24 _snake_case : Union[str, Any] = 16 _snake_case : Optional[int] = 0.1 _snake_case : int = ViTMSNModel(snake_case__ ) _snake_case : Optional[int] = torch.hub.load_state_dict_from_url(snake_case__ , map_location="""cpu""" )["""target_encoder"""] _snake_case : List[str] = ViTImageProcessor(size=config.image_size ) remove_projection_head(snake_case__ ) _snake_case : List[str] = create_rename_keys(snake_case__ , base_model=snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_q_k_v(snake_case__ , snake_case__ , base_model=snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() _snake_case : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _snake_case : Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) _snake_case : str = ViTImageProcessor( size=config.image_size , image_mean=snake_case__ , image_std=snake_case__ ) _snake_case : Any = image_processor(images=snake_case__ , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) _snake_case : int = model(**snake_case__ ) _snake_case : List[Any] = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: _snake_case : Optional[Any] = torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] ) elif "b16" in checkpoint_url: _snake_case : str = torch.tensor([[14.28_89, -18.90_45, 11.72_81]] ) elif "l16" in checkpoint_url: _snake_case : Optional[int] = torch.tensor([[41.50_28, -22.86_81, 45.64_75]] ) elif "b4" in checkpoint_url: _snake_case : List[Any] = torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] ) else: _snake_case : Optional[int] = torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , snake_case__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A_ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
64
0
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _UpperCamelCase ( lowercase__ ): return getitem, k def _UpperCamelCase ( lowercase__ , lowercase__ ): return setitem, k, v def _UpperCamelCase ( lowercase__ ): return delitem, k def _UpperCamelCase ( lowercase__ , lowercase__ , *lowercase__ ): try: return fun(lowercase__ , *lowercase__ ), None except Exception as e: return None, e __lowerCAmelCase : Any =( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) __lowerCAmelCase : Optional[Any] =[ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] __lowerCAmelCase : Union[str, Any] =[ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] __lowerCAmelCase : int =[ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] __lowerCAmelCase : Optional[Any] =[ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __lowerCAmelCase : Optional[Any] =[ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( '''operations''' , ( pytest.param(_add_items , id='''add items''' ), pytest.param(_overwrite_items , id='''overwrite items''' ), pytest.param(_delete_items , id='''delete items''' ), pytest.param(_access_absent_items , id='''access absent items''' ), pytest.param(_add_with_resize_up , id='''add with resize up''' ), pytest.param(_add_with_resize_down , id='''add with resize down''' ), ) , ) def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : Optional[int] = HashMap(initial_block_size=4 ) __SCREAMING_SNAKE_CASE : int = {} for _, (fun, *args) in enumerate(lowercase__ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = _run_operation(lowercase__ , lowercase__ , *lowercase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = _run_operation(lowercase__ , lowercase__ , *lowercase__ ) assert my_res == py_res assert str(lowercase__ ) == str(lowercase__ ) assert set(lowercase__ ) == set(lowercase__ ) assert len(lowercase__ ) == len(lowercase__ ) assert set(my.items() ) == set(py.items() ) def _UpperCamelCase ( ): def is_public(lowercase__ ) -> bool: return not name.startswith('''_''' ) __SCREAMING_SNAKE_CASE : List[str] = {name for name in dir({} ) if is_public(lowercase__ )} __SCREAMING_SNAKE_CASE : List[Any] = {name for name in dir(HashMap() ) if is_public(lowercase__ )} assert dict_public_names > hash_public_names
9
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str ): """simple docstring""" _snake_case : Optional[Any] = list(snake_case__ ) _snake_case : List[Any] = list(snake_case__ ) _snake_case : List[Any] = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count += 1 _snake_case : Any = """_""" if count > 1: return False else: return "".join(snake_case__ ) def UpperCAmelCase__ (snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [] while True: _snake_case : Union[str, Any] = ["""$"""] * len(snake_case__ ) _snake_case : int = [] for i in range(len(snake_case__ ) ): for j in range(i + 1 , len(snake_case__ ) ): _snake_case : List[Any] = compare_string(binary[i] , binary[j] ) if k is False: _snake_case : Dict = """*""" _snake_case : List[Any] = """*""" temp.append("""X""" ) for i in range(len(snake_case__ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case__ ) == 0: return pi _snake_case : Optional[int] = list(set(snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Sequence[float] ): """simple docstring""" _snake_case : Optional[int] = [] for minterm in minterms: _snake_case : Any = """""" for _ in range(snake_case__ ): _snake_case : Optional[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case__ ) return temp def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : int ): """simple docstring""" _snake_case : Dict = list(snake_case__ ) _snake_case : List[str] = list(snake_case__ ) _snake_case : Tuple = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCAmelCase__ (snake_case__ : list[list[int]] , snake_case__ : list[str] ): """simple docstring""" _snake_case : Any = [] _snake_case : Union[str, Any] = [0] * len(snake_case__ ) for i in range(len(chart[0] ) ): _snake_case : Tuple = 0 _snake_case : str = -1 for j in range(len(snake_case__ ) ): if chart[j][i] == 1: count += 1 _snake_case : Union[str, Any] = j if count == 1: _snake_case : Union[str, Any] = 1 for i in range(len(snake_case__ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case__ ) ): _snake_case : List[Any] = 0 temp.append(prime_implicants[i] ) while True: _snake_case : Optional[int] = 0 _snake_case : str = -1 _snake_case : Any = 0 for i in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _snake_case : Dict = count_n _snake_case : Dict = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case__ ) ): _snake_case : Optional[Any] = 0 def UpperCAmelCase__ (snake_case__ : list[str] , snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [[0 for x in range(len(snake_case__ ) )] for x in range(len(snake_case__ ) )] for i in range(len(snake_case__ ) ): _snake_case : Any = prime_implicants[i].count("""_""" ) for j in range(len(snake_case__ ) ): if is_for_table(prime_implicants[i] , binary[j] , snake_case__ ): _snake_case : Tuple = 1 return chart def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = int(input("""Enter the no. of variables\n""" ) ) _snake_case : List[str] = [ float(snake_case__ ) for x in input( """Enter the decimal representation of Minterms 'Spaces Separated'\n""" ).split() ] _snake_case : List[str] = decimal_to_binary(snake_case__ , snake_case__ ) _snake_case : str = check(snake_case__ ) print("""Prime Implicants are:""" ) print(snake_case__ ) _snake_case : int = prime_implicant_chart(snake_case__ , snake_case__ ) _snake_case : str = selection(snake_case__ , snake_case__ ) print("""Essential Prime Implicants are:""" ) print(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
64
0
import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin __A = random.Random() def lowerCAmelCase_ ( __a , __a=1.0 , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if rng is None: lowerCamelCase__: Union[str, Any] =global_rng lowerCamelCase__: List[Any] =[] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__(self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=7 , UpperCAmelCase_ : Any=400 , UpperCAmelCase_ : Dict=2_000 , UpperCAmelCase_ : Union[str, Any]=1 , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : int=16_000 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=True , ) ->List[str]: '''simple docstring''' lowerCamelCase__: List[str] =parent lowerCamelCase__: int =batch_size lowerCamelCase__: Tuple =min_seq_length lowerCamelCase__: Dict =max_seq_length lowerCamelCase__: Optional[int] =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCamelCase__: Any =feature_size lowerCamelCase__: List[str] =padding_value lowerCamelCase__: Union[str, Any] =sampling_rate lowerCamelCase__: Dict =return_attention_mask lowerCamelCase__: Optional[Any] =do_normalize def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict: '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : str=False) ->List[Any]: '''simple docstring''' def _flatten(UpperCAmelCase_ : Optional[int]): return list(itertools.chain(*UpperCAmelCase_)) if equal_length: lowerCamelCase__: List[Any] =floats_list((self.batch_size, self.max_seq_length)) else: # make sure that inputs increase in size lowerCamelCase__: Dict =[ _flatten(floats_list((x, self.feature_size))) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff) ] if numpify: lowerCamelCase__: List[str] =[np.asarray(UpperCAmelCase_) for x in speech_inputs] return speech_inputs class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = WavaVecaFeatureExtractor def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any: '''simple docstring''' lowerCamelCase__: Any =WavaVecaFeatureExtractionTester(self) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : List[Any]) ->str: '''simple docstring''' self.assertTrue(np.all(np.mean(UpperCAmelCase_ , axis=0) < 1E-3)) self.assertTrue(np.all(np.abs(np.var(UpperCAmelCase_ , axis=0) - 1) < 1E-3)) def SCREAMING_SNAKE_CASE_ (self : int) ->int: '''simple docstring''' lowerCamelCase__: str =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) # create three inputs of length 800, 1000, and 1200 lowerCamelCase__: Optional[Any] =[floats_list((1, x))[0] for x in range(800 , 1_400 , 200)] lowerCamelCase__: Any =[np.asarray(UpperCAmelCase_) for speech_input in speech_inputs] # Test not batched input lowerCamelCase__: str =feat_extract(speech_inputs[0] , return_tensors="np").input_values lowerCamelCase__: int =feat_extract(np_speech_inputs[0] , return_tensors="np").input_values self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3)) # Test batched lowerCamelCase__: List[str] =feat_extract(UpperCAmelCase_ , return_tensors="np").input_values lowerCamelCase__: Dict =feat_extract(UpperCAmelCase_ , return_tensors="np").input_values for enc_seq_a, enc_seq_a in zip(UpperCAmelCase_ , UpperCAmelCase_): self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3)) # Test 2-D numpy arrays are batched. lowerCamelCase__: Union[str, Any] =[floats_list((1, x))[0] for x in (800, 800, 800)] lowerCamelCase__: Union[str, Any] =np.asarray(UpperCAmelCase_) lowerCamelCase__: Optional[int] =feat_extract(UpperCAmelCase_ , return_tensors="np").input_values lowerCamelCase__: Dict =feat_extract(UpperCAmelCase_ , return_tensors="np").input_values for enc_seq_a, enc_seq_a in zip(UpperCAmelCase_ , UpperCAmelCase_): self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3)) def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) lowerCamelCase__: Optional[int] =[floats_list((1, x))[0] for x in range(800 , 1_400 , 200)] lowerCamelCase__: List[Any] =["longest", "max_length", "do_not_pad"] lowerCamelCase__: Optional[Any] =[None, 1_600, None] for max_length, padding in zip(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: str =feat_extract(UpperCAmelCase_ , padding=UpperCAmelCase_ , max_length=UpperCAmelCase_ , return_tensors="np") lowerCamelCase__: Tuple =processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800]) self.assertTrue(input_values[0][800:].sum() < 1E-6) self._check_zero_mean_unit_variance(input_values[1][:1_000]) self.assertTrue(input_values[0][1_000:].sum() < 1E-6) self._check_zero_mean_unit_variance(input_values[2][:1_200]) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Dict: '''simple docstring''' lowerCamelCase__: Any =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) lowerCamelCase__: Union[str, Any] =range(800 , 1_400 , 200) lowerCamelCase__: Optional[int] =[floats_list((1, x))[0] for x in lengths] lowerCamelCase__: Any =["longest", "max_length", "do_not_pad"] lowerCamelCase__: int =[None, 1_600, None] for max_length, padding in zip(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =feat_extract(UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding=UpperCAmelCase_) lowerCamelCase__: Any =processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800]) self._check_zero_mean_unit_variance(input_values[1][:1_000]) self._check_zero_mean_unit_variance(input_values[2][:1_200]) def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Tuple =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) lowerCamelCase__: Union[str, Any] =[floats_list((1, x))[0] for x in range(800 , 1_400 , 200)] lowerCamelCase__: Tuple =feat_extract( UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=1_000 , padding="max_length" , return_tensors="np") lowerCamelCase__: int =processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800]) self._check_zero_mean_unit_variance(input_values[1]) self._check_zero_mean_unit_variance(input_values[2]) def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: Dict =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) lowerCamelCase__: Any =[floats_list((1, x))[0] for x in range(800 , 1_400 , 200)] lowerCamelCase__: str =feat_extract( UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=1_000 , padding="longest" , return_tensors="np") lowerCamelCase__: int =processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800]) self._check_zero_mean_unit_variance(input_values[1, :1_000]) self._check_zero_mean_unit_variance(input_values[2]) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_000)) lowerCamelCase__: Optional[Any] =[floats_list((1, x))[0] for x in range(800 , 1_400 , 200)] lowerCamelCase__: str =feat_extract( UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=2_000 , padding="longest" , return_tensors="np") lowerCamelCase__: int =processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800]) self._check_zero_mean_unit_variance(input_values[1, :1_000]) self._check_zero_mean_unit_variance(input_values[2]) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_200)) @require_torch def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Any: '''simple docstring''' import torch lowerCamelCase__: Tuple =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) lowerCamelCase__: int =np.random.rand(100).astype(np.floataa) lowerCamelCase__: Any =np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCamelCase__: str =feature_extractor.pad([{"input_values": inputs}] , return_tensors="np") self.assertTrue(np_processed.input_values.dtype == np.floataa) lowerCamelCase__: Any =feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt") self.assertTrue(pt_processed.input_values.dtype == torch.floataa) @slow @require_torch def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[int]: '''simple docstring''' for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: lowerCamelCase__: Optional[int] =WavaVecaConfig.from_pretrained(UpperCAmelCase_) lowerCamelCase__: List[str] =WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase_) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == "layer")
10
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" stooge(snake_case__ , 0 , len(snake_case__ ) - 1 ) return arr def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int ): """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _snake_case , _snake_case : Tuple = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _snake_case : Dict = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case__ , i + t , (snake_case__) ) # Recursively sort first 2/3 elements stooge(snake_case__ , snake_case__ , (h - t) ) if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(stooge_sort(unsorted))
64
0
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(a) , "Tatoeba directory does not exist.") class lowerCAmelCase__ ( unittest.TestCase): '''simple docstring''' @cached_property def _lowerCamelCase ( self) -> str: _A : List[str] = tempfile.mkdtemp() return TatoebaConverter(save_dir=__lowerCamelCase) @slow def _lowerCamelCase ( self) -> Tuple: self.resolver.convert_models(["heb-eng"]) @slow def _lowerCamelCase ( self) -> str: _A , _A : Any = self.resolver.write_model_card("opus-mt-he-en" , dry_run=__lowerCamelCase) assert mmeta["long_pair"] == "heb-eng"
11
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase( metaclass=__a ): '''simple docstring''' lowercase__ = ["note_seq"] def __init__( self: Dict, *a_: Union[str, Any], **a_: List[str] ): '''simple docstring''' requires_backends(self, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Optional[int], *a_: Any, **a_: Optional[Any] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] ) @classmethod def UpperCamelCase_ ( cls: Tuple, *a_: Optional[Any], **a_: List[str] ): '''simple docstring''' requires_backends(cls, ["""note_seq"""] )
64
0
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase__( __lowerCamelCase): def __init__( self: str , UpperCamelCase_: int , UpperCamelCase_: List[Any] , UpperCamelCase_: str=10_24 , UpperCamelCase_: int=10_24 , UpperCamelCase_: Any=3.6 ): __lowerCamelCase = tokenizer __lowerCamelCase = tokenizer.bos_token_id __lowerCamelCase = dataset __lowerCamelCase = seq_length __lowerCamelCase = seq_length * chars_per_token * num_of_sequences def __iter__( self: Optional[int] ): __lowerCamelCase = iter(self.dataset ) __lowerCamelCase = True while more_examples: __lowerCamelCase, __lowerCamelCase = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(UpperCamelCase_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: __lowerCamelCase = False break __lowerCamelCase = tokenizer(UpperCamelCase_ , truncation=UpperCamelCase_ )["""input_ids"""] __lowerCamelCase = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(UpperCamelCase_ ) , self.seq_length ): __lowerCamelCase = all_token_ids[i : i + self.seq_length] if len(UpperCamelCase_ ) == self.seq_length: yield torch.tensor(UpperCamelCase_ ) def lowerCamelCase__ ( A__ : Tuple ): '''simple docstring''' __lowerCamelCase = {"""streaming""": True} __lowerCamelCase = load_dataset(args.dataset_name , split="""train""" , **A__ ) __lowerCamelCase = ConstantLengthDataset(A__ , A__ , seq_length=args.seq_length ) __lowerCamelCase = DataLoader(A__ , batch_size=args.batch_size ) return eval_dataloader def lowerCamelCase__ ( A__ : List[str] ): '''simple docstring''' model.eval() __lowerCamelCase = [] for step, batch in enumerate(A__ ): with torch.no_grad(): __lowerCamelCase = model(A__ , labels=A__ ) __lowerCamelCase = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(A__ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __lowerCamelCase = torch.mean(torch.cat(A__ ) ) try: __lowerCamelCase = torch.exp(A__ ) except OverflowError: __lowerCamelCase = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator UpperCAmelCase_ = Accelerator() # Parse configuration UpperCAmelCase_ = HfArgumentParser(EvaluationArguments) UpperCAmelCase_ = parser.parse_args() set_seed(args.seed) # Logging UpperCAmelCase_ = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained(args.model_ckpt) UpperCAmelCase_ = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader UpperCAmelCase_ = create_dataloader(args) # Prepare everything with our `accelerator`. UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') UpperCAmelCase_ , UpperCAmelCase_ = evaluate(args) logger.info(f"""loss/eval: {eval_loss}, perplexity: {perplexity}""")
12
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : int = data _snake_case : Dict = [0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def UpperCamelCase_ ( a_: Optional[Any], a_: Dict ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xffffffff def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) _snake_case : Optional[int] = self.data + padding + struct.pack(""">Q""", 8 * len(self.data ) ) return padded_data def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def UpperCamelCase_ ( self: Optional[Any], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = list(struct.unpack(""">16L""", a_ ) ) + [0] * 64 for i in range(16, 80 ): _snake_case : List[Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = self.padding() _snake_case : str = self.split_blocks() for block in self.blocks: _snake_case : Any = self.expand_block(a_ ) _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = self.h for i in range(0, 80 ): if 0 <= i < 20: _snake_case : int = (b & c) | ((~b) & d) _snake_case : str = 0X5a827999 elif 20 <= i < 40: _snake_case : Optional[int] = b ^ c ^ d _snake_case : str = 0X6ed9eba1 elif 40 <= i < 60: _snake_case : List[Any] = (b & c) | (b & d) | (c & d) _snake_case : List[Any] = 0X8f1bbcdc elif 60 <= i < 80: _snake_case : List[Any] = b ^ c ^ d _snake_case : int = 0Xca62c1d6 _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = ( self.rotate(a_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(a_, 30 ), c, d, ) _snake_case : Union[str, Any] = ( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = B"""Test String""" assert SHAaHash(snake_case__ ).final_hash() == hashlib.shaa(snake_case__ ).hexdigest() # noqa: S324 def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _snake_case : Union[str, Any] = parser.parse_args() _snake_case : List[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _snake_case : str = f.read() else: _snake_case : int = bytes(snake_case__ , """utf-8""" ) print(SHAaHash(snake_case__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
64
0
import os import pytest from transformers.dynamic_module_utils import get_imports lowerCAmelCase : str = """ import os """ lowerCAmelCase : Optional[Any] = """ def foo(): import os return False """ lowerCAmelCase : str = """ def foo(): def bar(): if True: import os return False return bar() """ lowerCAmelCase : Any = """ import os try: import bar except ImportError: raise ValueError() """ lowerCAmelCase : int = """ import os def foo(): try: import bar except ImportError: raise ValueError() """ lowerCAmelCase : Tuple = """ import os try: import bar except (ImportError, AttributeError): raise ValueError() """ lowerCAmelCase : Optional[Any] = """ import os try: import bar except ImportError as e: raise ValueError() """ lowerCAmelCase : List[str] = """ import os try: import bar except: raise ValueError() """ lowerCAmelCase : List[Any] = """ import os try: import bar import baz except ImportError: raise ValueError() """ lowerCAmelCase : Optional[Any] = """ import os try: import bar import baz except ImportError: x = 1 raise ValueError() """ lowerCAmelCase : Any = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize("case" , _UpperCAmelCase ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = os.path.join(_UpperCAmelCase , "test_file.py" ) with open(_UpperCAmelCase , "w" ) as _tmp_file: _tmp_file.write(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Any = get_imports(_UpperCAmelCase ) assert parsed_imports == ["os"]
13
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings A_ = r''' [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: title_sep (`str`, *optional*, defaults to `" / "`): Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`]. doc_sep (`str`, *optional*, defaults to `" // "`): Separator inserted between the text of the retrieved document and the original input when calling [`RagRetriever`]. n_docs (`int`, *optional*, defaults to 5): Number of documents to retrieve. max_combined_length (`int`, *optional*, defaults to 300): Max length of contextualized input returned by [`~RagRetriever.__call__`]. retrieval_vector_size (`int`, *optional*, defaults to 768): Dimensionality of the document embeddings indexed by [`RagRetriever`]. retrieval_batch_size (`int`, *optional*, defaults to 8): Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated [`RagRetriever`]. dataset (`str`, *optional*, defaults to `"wiki_dpr"`): A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids using `datasets.list_datasets()`). dataset_split (`str`, *optional*, defaults to `"train"`) Which split of the `dataset` to load. index_name (`str`, *optional*, defaults to `"compressed"`) The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and `"compressed"`. index_path (`str`, *optional*) The path to the serialized faiss index on disk. passages_path (`str`, *optional*): A path to text passages compatible with the faiss index. Required if using [`~models.rag.retrieval_rag.LegacyIndex`] use_dummy_dataset (`bool`, *optional*, defaults to `False`) Whether to load a "dummy" variant of the dataset specified by `dataset`. label_smoothing (`float`, *optional*, defaults to 0.0): Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed. do_marginalize (`bool`, *optional*, defaults to `False`): If `True`, the logits are marginalized over all documents by making use of `torch.nn.functional.log_softmax`. reduce_loss (`bool`, *optional*, defaults to `False`): Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation. do_deduplication (`bool`, *optional*, defaults to `True`): Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to `False` if used while training with distributed backend. exclude_bos_score (`bool`, *optional*, defaults to `False`): Whether or not to disregard the BOS token when computing the loss. output_retrieved(`bool`, *optional*, defaults to `False`): If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and `context_attention_mask` are returned. See returned tensors for more detail. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). forced_eos_token_id (`int`, *optional*): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`. ''' @add_start_docstrings(__a ) class lowercase( __a ): '''simple docstring''' lowercase__ = "rag" lowercase__ = True def __init__( self: Union[str, Any], a_: int=None, a_: Tuple=True, a_: Optional[int]=None, a_: List[str]=None, a_: int=None, a_: Optional[Any]=None, a_: List[str]=None, a_: Optional[Any]=" / ", a_: Tuple=" // ", a_: List[Any]=5, a_: Dict=300, a_: Tuple=768, a_: Optional[Any]=8, a_: int="wiki_dpr", a_: Any="train", a_: Optional[int]="compressed", a_: Optional[int]=None, a_: List[Any]=None, a_: Optional[Any]=False, a_: str=False, a_: Dict=0.0, a_: Union[str, Any]=True, a_: Union[str, Any]=False, a_: str=False, a_: List[str]=False, a_: Union[str, Any]=True, a_: Any=None, **a_: List[Any], ): '''simple docstring''' super().__init__( bos_token_id=a_, pad_token_id=a_, eos_token_id=a_, decoder_start_token_id=a_, forced_eos_token_id=a_, is_encoder_decoder=a_, prefix=a_, vocab_size=a_, **a_, ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _snake_case : Union[str, Any] = kwargs.pop("""question_encoder""" ) _snake_case : List[str] = question_encoder_config.pop("""model_type""" ) _snake_case : Union[str, Any] = kwargs.pop("""generator""" ) _snake_case : Any = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig _snake_case : Union[str, Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Optional[Any] = AutoConfig.for_model(a_, **a_ ) _snake_case : Any = reduce_loss _snake_case : Optional[int] = label_smoothing _snake_case : Dict = exclude_bos_score _snake_case : int = do_marginalize _snake_case : Optional[Any] = title_sep _snake_case : Any = doc_sep _snake_case : List[str] = n_docs _snake_case : Tuple = max_combined_length _snake_case : Optional[Any] = dataset _snake_case : Union[str, Any] = dataset_split _snake_case : Tuple = index_name _snake_case : Any = retrieval_vector_size _snake_case : Union[str, Any] = retrieval_batch_size _snake_case : str = passages_path _snake_case : Tuple = index_path _snake_case : List[Any] = use_dummy_dataset _snake_case : Optional[Any] = output_retrieved _snake_case : Tuple = do_deduplication _snake_case : Union[str, Any] = use_cache if self.forced_eos_token_id is None: _snake_case : Dict = getattr(self.generator, """forced_eos_token_id""", a_ ) @classmethod def UpperCamelCase_ ( cls: Any, a_: PretrainedConfig, a_: PretrainedConfig, **a_: Optional[Any] ): '''simple docstring''' return cls(question_encoder=question_encoder_config.to_dict(), generator=generator_config.to_dict(), **a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : Optional[int] = copy.deepcopy(self.__dict__ ) _snake_case : List[str] = self.question_encoder.to_dict() _snake_case : Tuple = self.generator.to_dict() _snake_case : Dict = self.__class__.model_type return output
64
0
import unittest from transformers import BigBirdConfig, 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 from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : List[Any]=56 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Union[str, Any]=7 , UpperCAmelCase__ : Optional[Any]="gelu_new" , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : str=512 , UpperCAmelCase__ : List[str]=16 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[str]="block_sparse" , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : Union[str, Any]=3 , ) ->Union[str, Any]: '''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 A__ = rescale_embeddings A__ = attention_type A__ = use_bias A__ = block_size A__ = num_random_blocks def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[Any]: '''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__ = BigBirdConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Optional[int]: '''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 UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) UpperCAmelCase__ = False UpperCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' A__ = FlaxBigBirdModelTester(self) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->str: '''simple docstring''' super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE ( self : Any) ->int: '''simple docstring''' super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE ( self : Dict) ->Dict: '''simple docstring''' super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' super().test_hidden_states_output() @slow def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' for model_class_name in self.all_model_classes: A__ = model_class_name.from_pretrained('''google/bigbird-roberta-base''') self.assertIsNotNone(UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Tuple: '''simple docstring''' if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE ( self : str) ->str: '''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(UpperCAmelCase__ , UpperCAmelCase__) A__ = model_class(UpperCAmelCase__) @jax.jit def model_jitted(UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any=None , **UpperCAmelCase__ : Tuple): return model(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , **UpperCAmelCase__) with self.subTest('''JIT Enabled'''): A__ = model_jitted(**UpperCAmelCase__).to_tuple() with self.subTest('''JIT Disabled'''): with jax.disable_jit(): A__ = model_jitted(**UpperCAmelCase__).to_tuple() self.assertEqual(len(UpperCAmelCase__) , len(UpperCAmelCase__)) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__): self.assertEqual(jitted_output.shape , output.shape) def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict=1e-5 , UpperCAmelCase__ : Union[str, Any]="outputs" , UpperCAmelCase__ : Optional[int]=None) ->List[str]: '''simple docstring''' if name.startswith('''outputs.attentions'''): return else: super().check_pt_flax_outputs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__)
14
"""simple docstring""" import os from typing import Dict, List, Tuple, TypeVar, Union A_ = TypeVar('''T''') A_ = Union[List[T], Tuple[T, ...]] A_ = Union[T, List[T], Dict[str, T]] A_ = Union[str, bytes, os.PathLike]
64
0
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline SCREAMING_SNAKE_CASE :Tuple = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std': True, 'scale': 0.1, 'eta': 0.0, 't_grad_cutoff': 2, 'device': 'cpu', } if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[str] = 'hopper-medium-v2' SCREAMING_SNAKE_CASE :Union[str, Any] = gym.make(env_name) SCREAMING_SNAKE_CASE :List[Any] = ValueGuidedRLPipeline.from_pretrained( 'bglick13/hopper-medium-v2-value-function-hor32', env=env, ) env.seed(0) SCREAMING_SNAKE_CASE :Optional[int] = env.reset() SCREAMING_SNAKE_CASE :Dict = 0 SCREAMING_SNAKE_CASE :Union[str, Any] = 0 SCREAMING_SNAKE_CASE :Any = 1000 SCREAMING_SNAKE_CASE :str = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy SCREAMING_SNAKE_CASE :Any = pipeline(obs, planning_horizon=32) # execute action in environment SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :Tuple = env.step(denorm_actions) SCREAMING_SNAKE_CASE :Optional[Any] = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( f'''Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:''' f''' {total_score}''' ) # save observations for rendering rollout.append(next_observation.copy()) SCREAMING_SNAKE_CASE :List[str] = next_observation except KeyboardInterrupt: pass print(f'''Total reward: {total_reward}''')
15
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] _snake_case : List[Any] = [] def generate(snake_case__ : int , snake_case__ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even _snake_case , _snake_case : Optional[Any] = arr[k - 1], arr[i] else: # k is odd _snake_case , _snake_case : List[str] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
64
0
"""simple docstring""" import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup lowerCAmelCase_ = logging.get_logger(__name__) class __A ( A_ ): '''simple docstring''' def __init__( self : Optional[int] ,**_snake_case : List[str] ) -> List[str]: """simple docstring""" requires_backends(self ,['''bs4'''] ) super().__init__(**_snake_case ) def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : Union[str, Any] ) -> Optional[int]: """simple docstring""" lowercase__ : Optional[int] = [] lowercase__ : int = [] lowercase__ : Optional[int] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag lowercase__ : Union[str, Any] = parent.find_all(child.name ,recursive=_snake_case ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(_snake_case ) else next(i for i, s in enumerate(_snake_case ,1 ) if s is child ) ) lowercase__ : List[str] = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def UpperCAmelCase ( self : Dict ,_snake_case : Any ) -> int: """simple docstring""" lowercase__ : str = BeautifulSoup(_snake_case ,'''html.parser''' ) lowercase__ : Union[str, Any] = [] lowercase__ : Tuple = [] lowercase__ : str = [] for element in html_code.descendants: if type(_snake_case ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue lowercase__ : Tuple = html.unescape(_snake_case ).strip() if not text_in_this_tag: continue all_doc_strings.append(_snake_case ) lowercase__ , lowercase__ : List[str] = self.xpath_soup(_snake_case ) stringaxtag_seq.append(_snake_case ) stringaxsubs_seq.append(_snake_case ) if len(_snake_case ) != len(_snake_case ): raise ValueError('''Number of doc strings and xtags does not correspond''' ) if len(_snake_case ) != len(_snake_case ): raise ValueError('''Number of doc strings and xsubs does not correspond''' ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def UpperCAmelCase ( self : int ,_snake_case : Dict ,_snake_case : int ) -> List[str]: """simple docstring""" lowercase__ : int = '''''' for tagname, subs in zip(_snake_case ,_snake_case ): xpath += f"""/{tagname}""" if subs != 0: xpath += f"""[{subs}]""" return xpath def __call__( self : int ,_snake_case : Optional[int] ) -> BatchFeature: """simple docstring""" lowercase__ : List[str] = False # Check that strings has a valid type if isinstance(_snake_case ,_snake_case ): lowercase__ : List[Any] = True elif isinstance(_snake_case ,(list, tuple) ): if len(_snake_case ) == 0 or isinstance(html_strings[0] ,_snake_case ): lowercase__ : Union[str, Any] = True if not valid_strings: raise ValueError( '''HTML strings must of type `str`, `List[str]` (batch of examples), ''' f"""but is of type {type(_snake_case )}.""" ) lowercase__ : Union[str, Any] = bool(isinstance(_snake_case ,(list, tuple) ) and (isinstance(html_strings[0] ,_snake_case )) ) if not is_batched: lowercase__ : Optional[Any] = [html_strings] # Get nodes + xpaths lowercase__ : int = [] lowercase__ : Optional[int] = [] for html_string in html_strings: lowercase__ , lowercase__ , lowercase__ : List[Any] = self.get_three_from_single(_snake_case ) nodes.append(_snake_case ) lowercase__ : int = [] for node, tag_list, sub_list in zip(_snake_case ,_snake_case ,_snake_case ): lowercase__ : Optional[Any] = self.construct_xpath(_snake_case ,_snake_case ) xpath_strings.append(_snake_case ) xpaths.append(_snake_case ) # return as Dict lowercase__ : str = {'''nodes''': nodes, '''xpaths''': xpaths} lowercase__ : List[Any] = BatchFeature(data=_snake_case ,tensor_type=_snake_case ) return encoded_inputs
16
"""simple docstring""" from math import factorial A_ = {str(d): factorial(d) for d in range(10)} def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(snake_case__ ) ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , snake_case__ ) if sum_of_digit_factorial(snake_case__ ) == i ) if __name__ == "__main__": print(F'''{solution() = }''')
64
0
"""simple docstring""" from __future__ import annotations class _lowerCAmelCase : """simple docstring""" def __init__( self : Optional[Any], UpperCAmelCase__ : list[list[int]] ): __lowercase = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(UpperCAmelCase__ ) != 0: __lowercase = len(rows[0] ) if cols == 0: raise error for row in rows: if len(UpperCAmelCase__ ) != cols: raise error for value in row: if not isinstance(UpperCAmelCase__, (int, float) ): raise error __lowercase = rows else: __lowercase = [] def _lowercase ( self : int ): return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )] @property def _lowercase ( self : str ): return len(self.rows ) @property def _lowercase ( self : str ): return len(self.rows[0] ) @property def _lowercase ( self : List[str] ): return (self.num_rows, self.num_columns) @property def _lowercase ( self : int ): return self.order[0] == self.order[1] def _lowercase ( self : Union[str, Any] ): __lowercase = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows )] for row_num in range(self.num_rows ) ] return Matrix(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ): if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0] ) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns ) ) def _lowercase ( self : Dict ): return bool(self.determinant() ) def _lowercase ( self : Tuple, UpperCAmelCase__ : int, UpperCAmelCase__ : int ): __lowercase = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns ) if other_column != column ] for other_row in range(self.num_rows ) if other_row != row ] return Matrix(UpperCAmelCase__ ).determinant() def _lowercase ( self : Optional[Any], UpperCAmelCase__ : int, UpperCAmelCase__ : int ): if (row + column) % 2 == 0: return self.get_minor(UpperCAmelCase__, UpperCAmelCase__ ) return -1 * self.get_minor(UpperCAmelCase__, UpperCAmelCase__ ) def _lowercase ( self : Optional[int] ): return Matrix( [ [self.get_minor(UpperCAmelCase__, UpperCAmelCase__ ) for column in range(self.num_columns )] for row in range(self.num_rows ) ] ) def _lowercase ( self : Tuple ): return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns ) ] for row in range(self.minors().num_rows ) ] ) def _lowercase ( self : List[str] ): __lowercase = [ [self.cofactors().rows[column][row] for column in range(self.num_columns )] for row in range(self.num_rows ) ] return Matrix(UpperCAmelCase__ ) def _lowercase ( self : str ): __lowercase = self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse" ) return self.adjugate() * (1 / determinant) def __repr__( self : List[str] ): return str(self.rows ) def __str__( self : int ): if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0] ) ) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(UpperCAmelCase__ ) for value in row] ) + ".]" for row in self.rows ] ) + "]" ) def _lowercase ( self : List[Any], UpperCAmelCase__ : list[int], UpperCAmelCase__ : int | None = None ): __lowercase = TypeError("Row must be a list containing all ints and/or floats" ) if not isinstance(UpperCAmelCase__, UpperCAmelCase__ ): raise type_error for value in row: if not isinstance(UpperCAmelCase__, (int, float) ): raise type_error if len(UpperCAmelCase__ ) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(UpperCAmelCase__ ) else: __lowercase = self.rows[0:position] + [row] + self.rows[position:] def _lowercase ( self : List[str], UpperCAmelCase__ : list[int], UpperCAmelCase__ : int | None = None ): __lowercase = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(UpperCAmelCase__, UpperCAmelCase__ ): raise type_error for value in column: if not isinstance(UpperCAmelCase__, (int, float) ): raise type_error if len(UpperCAmelCase__ ) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: __lowercase = [self.rows[i] + [column[i]] for i in range(self.num_rows )] else: __lowercase = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows ) ] def __eq__( self : List[Any], UpperCAmelCase__ : object ): if not isinstance(UpperCAmelCase__, UpperCAmelCase__ ): return NotImplemented return self.rows == other.rows def __ne__( self : Any, UpperCAmelCase__ : object ): return not self == other def __neg__( self : Tuple ): return self * -1 def __add__( self : List[Any], UpperCAmelCase__ : Matrix ): if self.order != other.order: raise ValueError("Addition requires matrices of the same order" ) return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __sub__( self : int, UpperCAmelCase__ : Matrix ): if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order" ) return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __mul__( self : str, UpperCAmelCase__ : Matrix | int | float ): if isinstance(UpperCAmelCase__, (int, float) ): return Matrix( [[int(element * other ) for element in row] for row in self.rows] ) elif isinstance(UpperCAmelCase__, UpperCAmelCase__ ): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(UpperCAmelCase__, UpperCAmelCase__ ) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__( self : Any, UpperCAmelCase__ : int ): if not isinstance(UpperCAmelCase__, UpperCAmelCase__ ): raise TypeError("A Matrix can only be raised to the power of an int" ) if not self.is_square: raise ValueError("Only square matrices can be raised to a power" ) if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) __lowercase = self for _ in range(other - 1 ): result *= self return result @classmethod def _lowercase ( cls : str, UpperCAmelCase__ : list[int], UpperCAmelCase__ : list[int] ): return sum(row[i] * column[i] for i in range(len(UpperCAmelCase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
17
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : int ): """simple docstring""" if len(snake_case__ ) < k or k < 0: raise ValueError("""Invalid Input""" ) _snake_case : Optional[int] = sum(array[:k] ) for i in range(len(snake_case__ ) - k ): _snake_case : Optional[Any] = current_sum - array[i] + array[i + k] _snake_case : List[str] = max(snake_case__ , snake_case__ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() A_ = [randint(-10_00, 10_00) for i in range(1_00)] A_ = randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
64
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=A__ ) class a__ ( A__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization A = field(default='question-answering-extractive' , metadata={'include_in_asdict_even_if_is_default': True} ) A = Features({'question': Value('string' ), 'context': Value('string' )} ) A = Features( { 'answers': Sequence( { 'text': Value('string' ), 'answer_start': Value('int32' ), } ) } ) A = "question" A = "context" A = "answers" @property def __UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
18
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } A_ = { '''yjernite/retribert-base-uncased''': 5_12, } A_ = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = RetriBertTokenizer lowercase__ = ["input_ids", "attention_mask"] def __init__( self: int, a_: int=None, a_: Dict=None, a_: Any=True, a_: int="[UNK]", a_: Any="[SEP]", a_: List[Any]="[PAD]", a_: List[Any]="[CLS]", a_: str="[MASK]", a_: Dict=True, a_: Optional[int]=None, **a_: Tuple, ): '''simple docstring''' super().__init__( a_, tokenizer_file=a_, do_lower_case=a_, unk_token=a_, sep_token=a_, pad_token=a_, cls_token=a_, mask_token=a_, tokenize_chinese_chars=a_, strip_accents=a_, **a_, ) _snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", a_ ) != do_lower_case or normalizer_state.get("""strip_accents""", a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", a_ ) != tokenize_chinese_chars ): _snake_case : Dict = getattr(a_, normalizer_state.pop("""type""" ) ) _snake_case : List[Any] = do_lower_case _snake_case : List[str] = strip_accents _snake_case : Tuple = tokenize_chinese_chars _snake_case : Tuple = normalizer_class(**a_ ) _snake_case : List[str] = do_lower_case def UpperCamelCase_ ( self: Any, a_: str, a_: Optional[int]=None ): '''simple docstring''' _snake_case : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self: List[str], a_: List[int], a_: Optional[List[int]] = None ): '''simple docstring''' _snake_case : Union[str, Any] = [self.sep_token_id] _snake_case : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self: Dict, a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : Union[str, Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ )
64
0
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _SCREAMING_SNAKE_CASE ( snake_case_ , unittest.TestCase ): lowerCAmelCase__ = XLMProphetNetTokenizer lowerCAmelCase__ = False lowerCAmelCase__ = True def SCREAMING_SNAKE_CASE_( self ) -> Any: super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ = XLMProphetNetTokenizer(lowercase , keep_accents=lowercase ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_( self ) -> List[str]: lowerCamelCase_ = "[PAD]" lowerCamelCase_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Any: lowerCamelCase_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "[PAD]" ) self.assertEqual(vocab_keys[1] , "[CLS]" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(lowercase ) , 1012 ) def SCREAMING_SNAKE_CASE_( self ) -> str: self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ = XLMProphetNetTokenizer(lowercase , keep_accents=lowercase ) lowerCamelCase_ = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowercase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase , [ 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", "é", ".", ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(lowercase ) self.assertListEqual( lowercase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , [ 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]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_( self ) -> Tuple: return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased" ) @slow def SCREAMING_SNAKE_CASE_( self ) -> Dict: lowerCamelCase_ = "Hello World!" lowerCamelCase_ = [35389, 6672, 49, 2] self.assertListEqual(lowercase , self.big_tokenizer.encode(lowercase ) ) @slow def SCREAMING_SNAKE_CASE_( self ) -> str: # fmt: off lowerCamelCase_ = {"input_ids": [[11073, 82783, 18, 26, 82783, 549, 51540, 248, 17209, 1301, 217, 20, 215186, 1325, 147, 17209, 1301, 217, 20, 56370, 53, 122020, 20, 16477, 27, 87355, 4548, 20, 4728, 78392, 17, 159969, 18, 26, 24491, 629, 15, 538, 22704, 5439, 15, 2788, 24491, 9885, 15, 43534, 605, 15, 814, 18403, 33200, 29, 15, 43534, 24458, 12410, 111, 24966, 83669, 9637, 144068, 26, 850, 22346, 27, 147, 24966, 83669, 83490, 26, 39113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 122020, 115785, 34, 816, 1339, 46887, 18, 147, 53905, 1951, 42238, 41170, 17732, 834, 436, 15, 27523, 98733, 217, 147, 5542, 4981, 930, 17347, 16, 2], [20091, 629, 94, 82786, 58, 490, 20, 1528, 84, 53905, 344, 80592, 110128, 18822, 5267, 1306, 62, 152537, 308, 7997, 401, 124427, 549, 35442, 225, 109, 15055, 25748, 147, 7119, 43712, 34, 767, 135366, 18, 16, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63784, 119466, 17, 147808, 88214, 18, 656, 81, 32, 3296, 10280, 16, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=lowercase , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
19
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CodeGenTokenizer lowercase__ = CodeGenTokenizerFast lowercase__ = True lowercase__ = {"add_prefix_space": True} lowercase__ = False def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _snake_case : Tuple = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] _snake_case : Tuple = dict(zip(a_, range(len(a_ ) ) ) ) _snake_case : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _snake_case : List[Any] = {"""unk_token""": """<unk>"""} _snake_case : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) _snake_case : Optional[Any] = 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(a_ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(a_ ) ) def UpperCamelCase_ ( self: Any, **a_: int ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Any, **a_: str ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Dict ): '''simple docstring''' _snake_case : Union[str, Any] = """lower newer""" _snake_case : Tuple = """lower newer""" return input_text, output_text def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) _snake_case : Optional[Any] = """lower newer""" _snake_case : Optional[int] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] _snake_case : int = tokenizer.tokenize(a_, add_prefix_space=a_ ) self.assertListEqual(a_, a_ ) _snake_case : str = tokens + [tokenizer.unk_token] _snake_case : Optional[int] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : int = self.get_tokenizer() _snake_case : int = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : Dict = """lower newer""" # Testing tokenization _snake_case : Dict = tokenizer.tokenize(a_, add_prefix_space=a_ ) _snake_case : List[str] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids without special tokens _snake_case : Optional[Any] = tokenizer.encode(a_, add_special_tokens=a_, add_prefix_space=a_ ) _snake_case : Tuple = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids with special tokens _snake_case : Tuple = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : int = tokenizer.encode(a_, add_prefix_space=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) # Testing the unknown token _snake_case : Tuple = tokens + [rust_tokenizer.unk_token] _snake_case : List[Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Dict, *a_: Dict, **a_: int ): '''simple docstring''' pass def UpperCamelCase_ ( self: int, a_: List[Any]=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : List[Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) # Simple input _snake_case : Any = """This is a simple input""" _snake_case : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Optional[int] = ("""This is a simple input""", """This is a pair""") _snake_case : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) # Pair input self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token="""<pad>""" ) # Simple input _snake_case : List[Any] = """This is a simple input""" _snake_case : int = ["""This is a simple input looooooooong""", """This is a simple input"""] _snake_case : Any = ("""This is a simple input""", """This is a pair""") _snake_case : str = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] _snake_case : str = tokenizer.pad_token_id _snake_case : Optional[int] = tokenizer(a_, padding="""max_length""", max_length=30, return_tensors="""np""" ) _snake_case : Dict = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) _snake_case : Tuple = tokenizer(*a_, padding="""max_length""", max_length=60, return_tensors="""np""" ) _snake_case : Optional[Any] = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Tuple = """$$$""" _snake_case : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=a_, add_bos_token=a_ ) _snake_case : str = """This is a simple input""" _snake_case : int = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Tuple = tokenizer(a_ ) _snake_case : Optional[Any] = tokenizer(a_ ) self.assertEqual(out_s.input_ids[0], a_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) _snake_case : Optional[int] = tokenizer.decode(out_s.input_ids ) _snake_case : int = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], a_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) _snake_case : Dict = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" _snake_case : Union[str, Any] = """\nif len_a > len_b: result = a\nelse: result = b""" _snake_case : Optional[Any] = tokenizer.encode(a_ ) _snake_case : Dict = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] _snake_case : Optional[Any] = tokenizer.decode(a_, truncate_before_pattern=a_ ) self.assertEqual(a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' pass
64
0