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""" import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase_ : str = [ """word_embeddings_layernorm.weight""", """word_embeddings_layernorm.bias""", """input_layernorm.weight""", """input_layernorm.bias""", """post_attention_layernorm.weight""", """post_attention_layernorm.bias""", """self_attention.dense.bias""", """mlp.dense_4h_to_h.bias""", """ln_f.weight""", """ln_f.bias""", ] lowerCamelCase_ : int = [ """mlp.dense_4h_to_h.weight""", """self_attention.dense.weight""", ] def _A ( lowercase , lowercase ): """simple docstring""" a ={ '''word_embeddings.weight''': '''word_embeddings.weight''', '''word_embeddings.norm.weight''': '''word_embeddings_layernorm.weight''', '''word_embeddings.norm.bias''': '''word_embeddings_layernorm.bias''', '''weight''': '''ln_f.weight''', '''bias''': '''ln_f.bias''', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks a =int(re.match(R'''.*layer_(\d*).*''' , lowercase )[1] ) layer_number -= 3 return f'''h.{layer_number}.''' + key def _A ( lowercase ): """simple docstring""" if dtype == torch.bool: return 1 / 8 a =re.search(R'''[^\d](\d+)$''' , str(lowercase ) ) if bit_search is None: raise ValueError(f'''`dtype` is not a valid dtype: {dtype}.''' ) a =int(bit_search.groups()[0] ) return bit_size // 8 def _A ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" # Construct model if bloom_config_file == "": a =BloomConfig() else: a =BloomConfig.from_json_file(lowercase ) if shard_model: a =os.listdir(lowercase ) a =sorted(filter(lambda lowercase : s.startswith('''layer''' ) and "model_00" in s , lowercase ) ) a ={'''weight_map''': {}, '''metadata''': {}} a =0 a =None a =BloomConfig() for j, file in enumerate(lowercase ): print('''Processing file: {}'''.format(lowercase ) ) a =None for i in range(lowercase ): # load all TP files a =file.replace('''model_00''' , f'''model_0{i}''' ) a =torch.load(os.path.join(lowercase , lowercase ) , map_location='''cpu''' ) # Rename keys in the transformers names a =list(temp.keys() ) for key in keys: a =temp.pop(lowercase ) if tensors is None: a =temp else: for key in tensors.keys(): if any(key.endswith(lowercase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel a =1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks a =torch.cat([tensors[key], temp[key]] , dim=lowercase ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(lowercase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): a =tensors[key] / pretraining_tp torch.save( lowercase , os.path.join( lowercase , '''pytorch_model_{}-of-{}.bin'''.format(str(j + 1 ).zfill(5 ) , str(len(lowercase ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): a =tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: a ='''pytorch_model_{}-of-{}.bin'''.format( str(j + 1 ).zfill(5 ) , str(len(lowercase ) ).zfill(5 ) ) a =BloomConfig() a =pytorch_dump_folder_path + '''/''' + CONFIG_NAME a =total_size with open(lowercase , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) with open(os.path.join(lowercase , WEIGHTS_NAME + '''.index.json''' ) , '''w''' , encoding='''utf-8''' ) as f: a =json.dumps(lowercase , indent=2 , sort_keys=lowercase ) + '''\n''' f.write(lowercase ) else: a =BloomModel(lowercase ) a =os.listdir(lowercase ) a =sorted(filter(lambda lowercase : s.startswith('''layer''' ) and "model_00" in s , lowercase ) ) a =None for i, file in enumerate(lowercase ): a =None for i in range(lowercase ): # load all TP files a =file.replace('''model_00''' , f'''model_0{i}''' ) a =torch.load(os.path.join(lowercase , lowercase ) , map_location='''cpu''' ) # Rename keys in the transformers names a =list(temp.keys() ) for key in keys: a =temp.pop(lowercase ) if tensors is None: a =temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(lowercase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel a =1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks a =torch.cat([tensors[key], temp[key]] , dim=lowercase ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(lowercase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): a =tensors[key] / pretraining_tp a =model.load_state_dict(lowercase , strict=lowercase ) assert not other_keys.unexpected_keys, f'''The keys {other_keys.unexpected_keys} are unexpected''' if missing_keys is None: a =set(other_keys.missing_keys ) else: a =missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, f'''The keys {missing_keys} are missing''' # Save pytorch-model os.makedirs(lowercase , exist_ok=lowercase ) a =pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a =pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'''Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}''' ) if config.torch_dtype is not None: a =model.to(config.torch_dtype ) torch.save(model.state_dict() , lowercase ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(lowercase , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCamelCase_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( """--bloom_checkpoint_path""", default=None, type=str, required=True, help="""Path to the Megatron-LM checkpoint path.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--bloom_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--shard_model""", action="""store_true""", help="""An optional setting to shard the output model \nThis enables sharding the converted checkpoint""", ) parser.add_argument( """--pretraining_tp""", default=4, type=int, help="""Pretraining TP rank that has been used when training the model in Megatron-LM \n""", ) lowerCamelCase_ : Dict = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
81
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def _UpperCAmelCase ( snake_case , snake_case , snake_case=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, F'{torch_layer} layer.weight does not match' _lowerCAmelCase = nn.Parameter(snake_case ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'{torch_layer} layer.bias does not match' _lowerCAmelCase = nn.Parameter(snake_case ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = np.asarray(weights[0] ) _lowerCAmelCase = np.asarray(weights[1] ) _lowerCAmelCase = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.self_attention.value , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.output.dense , torch.tensor(snake_case ).view(-1 , snake_case ).contiguous().transpose(0 , 1 ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = np.asarray(weights[0] ) _lowerCAmelCase = np.asarray(weights[1] ) _lowerCAmelCase = np.asarray(weights[2] ) _lowerCAmelCase = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.self_attention.key , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.self_attention.value , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.output.dense , torch.tensor(snake_case ).view(-1 , snake_case ).contiguous().transpose(0 , 1 ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = weights[0][0][0] _lowerCAmelCase = np.asarray(layer_norm_a[0] ) _lowerCAmelCase = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(snake_case ) , torch.tensor(snake_case ) , ) # lsh weights + output _lowerCAmelCase = weights[0][1] if len(snake_case ) < 4: set_layer_weights_in_torch_lsh(snake_case , torch_block.attention , snake_case ) else: set_layer_weights_in_torch_local(snake_case , torch_block.attention , snake_case ) # intermediate weighs _lowerCAmelCase = weights[2][0][1][2] # Chunked Feed Forward if len(snake_case ) == 4: _lowerCAmelCase = intermediate_weights[2] # layernorm 2 _lowerCAmelCase = np.asarray(intermediate_weights[0][0] ) _lowerCAmelCase = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(snake_case ) , torch.tensor(snake_case ) , ) # intermediate dense _lowerCAmelCase = np.asarray(intermediate_weights[1][0] ) _lowerCAmelCase = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(snake_case ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case ) , ) # intermediate out _lowerCAmelCase = np.asarray(intermediate_weights[4][0] ) _lowerCAmelCase = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(snake_case ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = torch_model.reformer # word embeds _lowerCAmelCase = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(snake_case ) , ) if isinstance(weights[3] , snake_case ): _lowerCAmelCase = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _lowerCAmelCase = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'{position_embeddings[emb_idx]} emb does not match' _lowerCAmelCase = nn.Parameter(torch.tensor(snake_case ) ) _lowerCAmelCase = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( snake_case ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _lowerCAmelCase = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(snake_case , snake_case , snake_case ) # output layer norm _lowerCAmelCase = np.asarray(weights[7][0] ) _lowerCAmelCase = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(snake_case ) , torch.tensor(snake_case ) , ) # output embeddings _lowerCAmelCase = np.asarray(weights[9][0] ) _lowerCAmelCase = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(snake_case ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = ReformerConfig.from_json_file(snake_case ) print(F'Building PyTorch model from configuration: {config}' ) _lowerCAmelCase = ReformerModelWithLMHead(snake_case ) with open(snake_case , """rb""" ) as f: _lowerCAmelCase = pickle.load(snake_case )["""weights"""] set_model_weights_in_torch(snake_case , snake_case , config.hidden_size ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , snake_case ) if __name__ == "__main__": A__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_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 Reformer model. \n""" """This 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_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
82
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm snake_case_ : List[Any] = logging.get_logger(__name__) @dataclass class lowercase__ ( lowercase ): lowercase__ = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self : int ,**lowerCamelCase__ : List[Any] ): '''simple docstring''' for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: _UpperCamelCase : List[str] = deprecated_arg[3:] setattr(self ,lowerCamelCase__ ,not kwargs.pop(lowerCamelCase__ ) ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) _UpperCamelCase : Optional[Any] = kwargs.pop('torchscript' ,self.torchscript ) _UpperCamelCase : List[str] = kwargs.pop('torch_xla_tpu_print_metrics' ,self.torch_xla_tpu_print_metrics ) _UpperCamelCase : Optional[Any] = kwargs.pop('fp16_opt_level' ,self.fpaa_opt_level ) super().__init__(**lowerCamelCase__ ) lowercase__ = field(default=lowercase , metadata={"""help""": """Trace the models using torchscript"""} ) lowercase__ = field(default=lowercase , metadata={"""help""": """Print Xla/PyTorch tpu metrics"""} ) lowercase__ = field( default="""O1""" , metadata={ """help""": ( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. """ """See details at https://nvidia.github.io/apex/amp.html""" ) } , ) @cached_property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' requires_backends(self ,['torch'] ) logger.info('PyTorch: setting up devices' ) if not self.cuda: _UpperCamelCase : Any = torch.device('cpu' ) _UpperCamelCase : Union[str, Any] = 0 elif is_torch_tpu_available(): _UpperCamelCase : Optional[Any] = xm.xla_device() _UpperCamelCase : Dict = 0 else: _UpperCamelCase : Tuple = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) _UpperCamelCase : List[Any] = torch.cuda.device_count() return device, n_gpu @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return is_torch_tpu_available() and self.tpu @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' requires_backends(self ,['torch'] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' requires_backends(self ,['torch'] ) return self._setup_devices[0] @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' requires_backends(self ,['torch'] ) return self._setup_devices[1] @property def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.n_gpu > 0
83
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class _SCREAMING_SNAKE_CASE ( A__ ): def __init__( self , __A , __A=None , __A=True , __A=None , **__A ) -> Tuple: lowerCAmelCase_ :int = parent lowerCAmelCase_ :Dict = config_class lowerCAmelCase_ :Union[str, Any] = has_text_modality lowerCAmelCase_ :Dict = kwargs lowerCAmelCase_ :Optional[Any] = common_properties def __lowerCAmelCase ( self ) -> Union[str, Any]: lowerCAmelCase_ :Any = self.config_class(**self.inputs_dict ) lowerCAmelCase_ :Any = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(__A , __A ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(__A ): try: setattr(__A , __A , __A ) self.parent.assertEqual( getattr(__A , __A ) , __A , msg=f"""`{name} value {idx} expected, but was {getattr(__A , __A )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(__A ): try: lowerCAmelCase_ :Dict = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(__A , __A ) , __A , msg=f"""`{name} value {idx} expected, but was {getattr(__A , __A )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def __lowerCAmelCase ( self ) -> List[Any]: lowerCAmelCase_ :Optional[Any] = self.config_class(**self.inputs_dict ) lowerCAmelCase_ :Tuple = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , __A ) def __lowerCAmelCase ( self ) -> int: lowerCAmelCase_ :Optional[int] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase_ :Optional[int] = os.path.join(__A , """config.json""" ) config_first.to_json_file(__A ) lowerCAmelCase_ :Optional[Any] = self.config_class.from_json_file(__A ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowerCAmelCase ( self ) -> Optional[Any]: lowerCAmelCase_ :int = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(__A ) lowerCAmelCase_ :List[Any] = self.config_class.from_pretrained(__A ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowerCAmelCase ( self ) -> int: lowerCAmelCase_ :Optional[int] = self.config_class(**self.inputs_dict ) lowerCAmelCase_ :str = """test""" with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase_ :List[str] = os.path.join(__A , __A ) config_first.save_pretrained(__A ) lowerCAmelCase_ :Tuple = self.config_class.from_pretrained(__A , subfolder=__A ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowerCAmelCase ( self ) -> Tuple: lowerCAmelCase_ :Any = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) lowerCAmelCase_ :int = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def __lowerCAmelCase ( self ) -> Any: if self.config_class.is_composition: return lowerCAmelCase_ :Dict = self.config_class() self.parent.assertIsNotNone(__A ) def __lowerCAmelCase ( self ) -> Any: lowerCAmelCase_ :str = copy.deepcopy(__A ) lowerCAmelCase_ :str = self.config_class(**__A ) lowerCAmelCase_ :Union[str, Any] = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(__A , __A ) != value: wrong_values.append((key, getattr(__A , __A ), value) ) if len(__A ) > 0: lowerCAmelCase_ :Optional[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def __lowerCAmelCase ( self ) -> List[str]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
84
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
'''simple docstring''' import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu _SCREAMING_SNAKE_CASE : int = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: _SCREAMING_SNAKE_CASE : List[Any] = json.load(f) @require_torch class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self , a__ ) -> Dict: '''simple docstring''' return FSMTTokenizer.from_pretrained(a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' snake_case_ = FSMTForConditionalGeneration.from_pretrained(a__ ).to(a__ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 2_6.0], ["ru-en", 2_2.0], ["en-de", 2_2.0], ["de-en", 2_9.0], ] ) @slow def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = F'facebook/wmt19-{pair}' snake_case_ = self.get_tokenizer(a__ ) snake_case_ = self.get_model(a__ ) snake_case_ = bleu_data[pair]["src"] snake_case_ = bleu_data[pair]["tgt"] snake_case_ = tokenizer(a__ , return_tensors="pt" , truncation=a__ , padding="longest" ).to(a__ ) snake_case_ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) snake_case_ = tokenizer.batch_decode( a__ , skip_special_tokens=a__ , clean_up_tokenization_spaces=a__ ) snake_case_ = calculate_bleu(a__ , a__ ) print(a__ ) self.assertGreaterEqual(scores["bleu"] , a__ )
85
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
"""simple docstring""" from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(_lowerCamelCase) class A__ ( _lowerCamelCase): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) self.check_model_type(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase , __lowerCAmelCase : List[Any] = {}, {} if padding is not None: __lowerCAmelCase : List[Any] = padding if truncation is not None: __lowerCAmelCase : Tuple = truncation if top_k is not None: __lowerCAmelCase : List[str] = top_k return preprocess_params, {}, postprocess_params def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (Image.Image, str) ) and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = {'image': image, 'question': question} else: __lowerCAmelCase : str = image __lowerCAmelCase : Tuple = super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return results def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ): __lowerCAmelCase : Tuple = load_image(inputs['image'] ) __lowerCAmelCase : List[Any] = self.tokenizer( inputs['question'] , return_tensors=self.framework , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(_SCREAMING_SNAKE_CASE ) return model_inputs def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = self.model(**_SCREAMING_SNAKE_CASE ) return model_outputs def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=5 ): if top_k > self.model.config.num_labels: __lowerCAmelCase : Any = self.model.config.num_labels if self.framework == "pt": __lowerCAmelCase : List[Any] = model_outputs.logits.sigmoid()[0] __lowerCAmelCase , __lowerCAmelCase : Dict = probs.topk(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f"Unsupported framework: {self.framework}" ) __lowerCAmelCase : int = scores.tolist() __lowerCAmelCase : Tuple = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )]
86
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): 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 , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller UpperCamelCase = 3 def lowercase_ ( _lowerCamelCase : int): print("Generating primitive root of p") while True: lowercase__ : str = random.randrange(3 , _lowerCamelCase) if pow(_lowerCamelCase , 2 , _lowerCamelCase) == 1: continue if pow(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) == 1: continue return g def lowercase_ ( _lowerCamelCase : int): print("Generating prime p...") lowercase__ : Optional[Any] = rabin_miller.generate_large_prime(_lowerCamelCase) # select large prime number. lowercase__ : int = primitive_root(_lowerCamelCase) # one primitive root on modulo p. lowercase__ : str = random.randrange(3 , _lowerCamelCase) # private_key -> have to be greater than 2 for safety. lowercase__ : List[Any] = cryptomath.find_mod_inverse(pow(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) , _lowerCamelCase) lowercase__ : Optional[Any] = (key_size, e_a, e_a, p) lowercase__ : Any = (key_size, d) return public_key, private_key def lowercase_ ( _lowerCamelCase : str , _lowerCamelCase : int): if os.path.exists(f'''{name}_pubkey.txt''') or os.path.exists(f'''{name}_privkey.txt'''): print("\nWARNING:") print( f'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n''' "Use a different name or delete these files and re-run this program.") sys.exit() lowercase__ , lowercase__ : Union[str, Any] = generate_key(_lowerCamelCase) print(f'''\nWriting public key to file {name}_pubkey.txt...''') with open(f'''{name}_pubkey.txt''' , "w") as fo: fo.write(f'''{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}''') print(f'''Writing private key to file {name}_privkey.txt...''') with open(f'''{name}_privkey.txt''' , "w") as fo: fo.write(f'''{private_key[0]},{private_key[1]}''') def lowercase_ ( ): print("Making key files...") make_key_files("elgamal" , 2048) print("Key files generation successful") if __name__ == "__main__": main()
87
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): 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 token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
import mpmath # for roots of unity import numpy as np class UpperCAmelCase_ : '''simple docstring''' def __init__( self : int , UpperCamelCase__ : str=None , UpperCamelCase__ : int=None ) -> List[str]: """simple docstring""" __magic_name__ = list(poly_a or [0] )[:] __magic_name__ = list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() __magic_name__ = len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() __magic_name__ = len(self.polyB ) # Add 0 to make lengths equal a power of 2 __magic_name__ = int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform __magic_name__ = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product __magic_name__ = self.__multiply() def _lowercase ( self : int , UpperCamelCase__ : Any ) -> Optional[int]: """simple docstring""" __magic_name__ = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(UpperCamelCase__ ) <= 1: return dft[0] # __magic_name__ = self.c_max_length // 2 while next_ncol > 0: __magic_name__ = [[] for i in range(UpperCamelCase__ )] __magic_name__ = self.root**next_ncol # First half of next step __magic_name__ = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(UpperCamelCase__ ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step __magic_name__ = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(UpperCamelCase__ ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update __magic_name__ = new_dft __magic_name__ = next_ncol // 2 return dft[0] def _lowercase ( self : Optional[Any] ) -> Tuple: """simple docstring""" __magic_name__ = self.__dft("""A""" ) __magic_name__ = self.__dft("""B""" ) __magic_name__ = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT __magic_name__ = 2 while next_ncol <= self.c_max_length: __magic_name__ = [[] for i in range(UpperCamelCase__ )] __magic_name__ = self.root ** (next_ncol // 2) __magic_name__ = 1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update __magic_name__ = new_inverse_c next_ncol *= 2 # Unpack __magic_name__ = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self : Optional[Any] ) -> Dict: """simple docstring""" __magic_name__ = """A = """ + """ + """.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) ) __magic_name__ = """B = """ + """ + """.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) ) __magic_name__ = """A*B = """ + """ + """.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) ) return F'''{a}\n{b}\n{c}''' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
'''simple docstring''' import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed __lowerCAmelCase = '''true''' def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=82 , lowerCAmelCase_=16 ) -> Union[str, Any]: set_seed(42 ) _a : Union[str, Any] = RegressionModel() _a : Dict = deepcopy(lowerCAmelCase_ ) _a : Any = RegressionDataset(length=lowerCAmelCase_ ) _a : List[str] = DataLoader(lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) model.to(accelerator.device ) _a , _a : int = accelerator.prepare(lowerCAmelCase_ , lowerCAmelCase_ ) return model, ddp_model, dataloader def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=False ) -> Optional[int]: _a : Optional[int] = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased' ) _a : Dict = load_dataset('glue' , 'mrpc' , split='validation' ) def tokenize_function(lowerCAmelCase_ ): _a : Optional[Any] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) return outputs with accelerator.main_process_first(): _a : int = dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) _a : Union[str, Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowerCAmelCase_ ): if use_longest: return tokenizer.pad(lowerCAmelCase_ , padding='longest' , return_tensors='pt' ) return tokenizer.pad(lowerCAmelCase_ , padding='max_length' , max_length=128 , return_tensors='pt' ) return DataLoader(lowerCAmelCase_ , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=16 ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str: _a : Optional[int] = Accelerator(dispatch_batches=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) _a : Optional[Any] = get_dataloader(lowerCAmelCase_ , not dispatch_batches ) _a : List[str] = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=lowerCAmelCase_ ) _a , _a : Optional[int] = accelerator.prepare(lowerCAmelCase_ , lowerCAmelCase_ ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: _a : Union[str, Any] = [] for batch in dataloader: _a , _a : Any = batch.values() with torch.no_grad(): _a : str = model(lowerCAmelCase_ ) _a , _a : Optional[int] = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) _a , _a : Dict = [], [] for logit, targ in logits_and_targets: logits.append(lowerCAmelCase_ ) targs.append(lowerCAmelCase_ ) _a , _a : Dict = torch.cat(lowerCAmelCase_ ), torch.cat(lowerCAmelCase_ ) return logits, targs def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=82 , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=16 ) -> List[Any]: _a , _a , _a : int = get_basic_setup(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _a , _a : Union[str, Any] = generate_predictions(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) assert ( len(lowerCAmelCase_ ) == num_samples ), f"""Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(lowerCAmelCase_ )}""" def __lowerCamelCase ( lowerCAmelCase_ = False , lowerCAmelCase_ = False ) -> List[Any]: _a : Optional[Any] = evaluate.load('glue' , 'mrpc' ) _a , _a : Any = get_mrpc_setup(lowerCAmelCase_ , lowerCAmelCase_ ) # First do baseline _a , _a , _a : str = setup['no'] model.to(lowerCAmelCase_ ) model.eval() for batch in dataloader: batch.to(lowerCAmelCase_ ) with torch.inference_mode(): _a : List[Any] = model(**lowerCAmelCase_ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=lowerCAmelCase_ , references=batch['labels'] ) _a : Any = metric.compute() # Then do distributed _a , _a , _a : int = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): _a : List[str] = model(**lowerCAmelCase_ ) _a : int = outputs.logits.argmax(dim=-1 ) _a : Optional[int] = batch['labels'] _a , _a : Dict = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=lowerCAmelCase_ , references=lowerCAmelCase_ ) _a : Any = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), f"""Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n""" def __lowerCamelCase ( ) -> str: _a : Optional[int] = Accelerator(split_batches=lowerCAmelCase_ , dispatch_batches=lowerCAmelCase_ ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`""" ) test_mrpc(lowerCAmelCase_ , lowerCAmelCase_ ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: _a : Optional[Any] = Accelerator(split_batches=lowerCAmelCase_ , dispatch_batches=lowerCAmelCase_ ) if accelerator.is_local_main_process: print(f"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99""" ) test_torch_metrics(lowerCAmelCase_ , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**' ) _a : int = Accelerator() test_torch_metrics(lowerCAmelCase_ , 512 ) accelerator.state._reset_state() def __lowerCamelCase ( lowerCAmelCase_ ) -> int: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
89
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
import json import unittest import numpy as np from huggingface_hub import hf_hub_download 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 transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def lowerCamelCase_ ( UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[str]="shi-labs/oneformer_demo" ) -> Union[str, Any]: """simple docstring""" with open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type='dataset' ) , 'r' ) as f: __lowerCamelCase = json.load(UpperCamelCase__ ) __lowerCamelCase = {} __lowerCamelCase = [] __lowerCamelCase = [] for key, info in class_info.items(): __lowerCamelCase = info['name'] class_names.append(info['name'] ) if info["isthing"]: thing_ids.append(int(UpperCamelCase__ ) ) __lowerCamelCase = thing_ids __lowerCamelCase = class_names return metadata class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=7 , lowerCamelCase__=3 , lowerCamelCase__=30 , lowerCamelCase__=400 , lowerCamelCase__=None , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=[0.5, 0.5, 0.5] , lowerCamelCase__=[0.5, 0.5, 0.5] , lowerCamelCase__=10 , lowerCamelCase__=False , lowerCamelCase__=255 , lowerCamelCase__="shi-labs/oneformer_demo" , lowerCamelCase__="ade20k_panoptic.json" , lowerCamelCase__=10 , ) -> str: '''simple docstring''' __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = do_resize __lowerCamelCase = {'shortest_edge': 32, 'longest_edge': 1_333} if size is None else size __lowerCamelCase = do_normalize __lowerCamelCase = image_mean __lowerCamelCase = image_std __lowerCamelCase = class_info_file __lowerCamelCase = prepare_metadata(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase = num_text __lowerCamelCase = repo_path # for the post_process_functions __lowerCamelCase = 2 __lowerCamelCase = 10 __lowerCamelCase = 10 __lowerCamelCase = 3 __lowerCamelCase = 4 __lowerCamelCase = num_labels __lowerCamelCase = do_reduce_labels __lowerCamelCase = ignore_index def lowercase_ ( self ) -> List[str]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__=False ) -> int: '''simple docstring''' if not batched: __lowerCamelCase = image_inputs[0] if isinstance(lowerCamelCase__ , Image.Image ): __lowerCamelCase , __lowerCamelCase = image.size else: __lowerCamelCase , __lowerCamelCase = image.shape[1], image.shape[2] if w < h: __lowerCamelCase = int(self.size['shortest_edge'] * h / w ) __lowerCamelCase = self.size['shortest_edge'] elif w > h: __lowerCamelCase = self.size['shortest_edge'] __lowerCamelCase = int(self.size['shortest_edge'] * w / h ) else: __lowerCamelCase = self.size['shortest_edge'] __lowerCamelCase = self.size['shortest_edge'] else: __lowerCamelCase = [] for image in image_inputs: __lowerCamelCase , __lowerCamelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCamelCase = max(lowerCamelCase__ , key=lambda lowerCamelCase__ : item[0] )[0] __lowerCamelCase = max(lowerCamelCase__ , key=lambda lowerCamelCase__ : item[1] )[1] return expected_height, expected_width def lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): """simple docstring""" snake_case_ = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string snake_case_ = image_processing_class def lowercase_ ( self ) -> Any: '''simple docstring''' __lowerCamelCase = OneFormerImageProcessorTester(self ) @property def lowercase_ ( self ) -> List[str]: '''simple docstring''' return self.image_processing_tester.prepare_image_processor_dict() def lowercase_ ( self ) -> List[Any]: '''simple docstring''' __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase__ , 'image_mean' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'image_std' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'do_normalize' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'do_resize' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'size' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'ignore_index' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'class_info_file' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'num_text' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'repo_path' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'metadata' ) ) self.assertTrue(hasattr(lowerCamelCase__ , 'do_reduce_labels' ) ) def lowercase_ ( self ) -> Tuple: '''simple docstring''' pass def lowercase_ ( self ) -> Dict: '''simple docstring''' # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , Image.Image ) # Test not batched input __lowerCamelCase = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values __lowerCamelCase , __lowerCamelCase = self.image_processing_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCamelCase , __lowerCamelCase = self.image_processing_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) __lowerCamelCase = image_processor( lowerCamelCase__ , ['semantic'] * len(lowerCamelCase__ ) , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def lowercase_ ( self ) -> Any: '''simple docstring''' # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase__ , numpify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , np.ndarray ) # Test not batched input __lowerCamelCase = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values __lowerCamelCase , __lowerCamelCase = self.image_processing_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCamelCase , __lowerCamelCase = self.image_processing_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) __lowerCamelCase = image_processor( lowerCamelCase__ , ['semantic'] * len(lowerCamelCase__ ) , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def lowercase_ ( self ) -> List[str]: '''simple docstring''' # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase__ , torchify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , torch.Tensor ) # Test not batched input __lowerCamelCase = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values __lowerCamelCase , __lowerCamelCase = self.image_processing_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCamelCase , __lowerCamelCase = self.image_processing_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) __lowerCamelCase = image_processor( lowerCamelCase__ , ['semantic'] * len(lowerCamelCase__ ) , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def lowercase_ ( self , lowerCamelCase__=False , lowerCamelCase__=False , lowerCamelCase__="np" ) -> List[Any]: '''simple docstring''' __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # prepare image and target __lowerCamelCase = self.image_processing_tester.num_labels __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase__ ) if with_segmentation_maps: __lowerCamelCase = num_labels if is_instance_map: __lowerCamelCase = list(range(lowerCamelCase__ ) ) * 2 __lowerCamelCase = dict(enumerate(lowerCamelCase__ ) ) __lowerCamelCase = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": __lowerCamelCase = [Image.fromarray(lowerCamelCase__ ) for annotation in annotations] __lowerCamelCase = image_processor( lowerCamelCase__ , ['semantic'] * len(lowerCamelCase__ ) , lowerCamelCase__ , return_tensors='pt' , instance_id_to_semantic_id=lowerCamelCase__ , pad_and_return_pixel_mask=lowerCamelCase__ , ) return inputs def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' pass def lowercase_ ( self ) -> Any: '''simple docstring''' def common(lowerCamelCase__=False , lowerCamelCase__=None ): __lowerCamelCase = self.comm_get_image_processor_inputs( with_segmentation_maps=lowerCamelCase__ , is_instance_map=lowerCamelCase__ , segmentation_type=lowerCamelCase__ ) __lowerCamelCase = inputs['mask_labels'] __lowerCamelCase = inputs['class_labels'] __lowerCamelCase = inputs['pixel_values'] __lowerCamelCase = inputs['text_inputs'] # check the batch_size for mask_label, class_label, text_input in zip(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(lowerCamelCase__ ) , self.image_processing_tester.num_text ) common() common(is_instance_map=lowerCamelCase__ ) common(is_instance_map=lowerCamelCase__ , segmentation_type='pil' ) common(is_instance_map=lowerCamelCase__ , segmentation_type='pil' ) def lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = np.zeros((20, 50) ) __lowerCamelCase = 1 __lowerCamelCase = 1 __lowerCamelCase = 1 __lowerCamelCase = binary_mask_to_rle(lowerCamelCase__ ) self.assertEqual(len(lowerCamelCase__ ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) __lowerCamelCase = self.image_processing_tester.get_fake_oneformer_outputs() __lowerCamelCase = fature_extractor.post_process_semantic_segmentation(lowerCamelCase__ ) self.assertEqual(len(lowerCamelCase__ ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) __lowerCamelCase = [(1, 4) for i in range(self.image_processing_tester.batch_size )] __lowerCamelCase = fature_extractor.post_process_semantic_segmentation(lowerCamelCase__ , target_sizes=lowerCamelCase__ ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def lowercase_ ( self ) -> List[str]: '''simple docstring''' __lowerCamelCase = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) __lowerCamelCase = self.image_processing_tester.get_fake_oneformer_outputs() __lowerCamelCase = image_processor.post_process_instance_segmentation(lowerCamelCase__ , threshold=0 ) self.assertTrue(len(lowerCamelCase__ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue('segmentation' in el ) self.assertTrue('segments_info' in el ) self.assertEqual(type(el['segments_info'] ) , lowerCamelCase__ ) self.assertEqual( el['segmentation'].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) __lowerCamelCase = self.image_processing_tester.get_fake_oneformer_outputs() __lowerCamelCase = image_processor.post_process_panoptic_segmentation(lowerCamelCase__ , threshold=0 ) self.assertTrue(len(lowerCamelCase__ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue('segmentation' in el ) self.assertTrue('segments_info' in el ) self.assertEqual(type(el['segments_info'] ) , lowerCamelCase__ ) self.assertEqual( el['segmentation'].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
90
'''simple docstring''' # Copyright 2021 The HuggingFace 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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_activation('''gelu''') self.assertTrue(torch.allclose(gelu_python(lowercase_) , torch_builtin(lowercase_))) self.assertFalse(torch.allclose(gelu_python(lowercase_) , gelu_new(lowercase_))) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) SCREAMING_SNAKE_CASE_ : Tuple = get_activation('''gelu''') SCREAMING_SNAKE_CASE_ : Optional[Any] = get_activation('''gelu_10''') SCREAMING_SNAKE_CASE_ : str = torch_builtin(lowercase_) SCREAMING_SNAKE_CASE_ : int = geluaa(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = torch.where(y_gelu_aa < 10.0 , 1 , 0) self.assertTrue(torch.max(lowercase_).item() == 10.0) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' get_activation('''gelu''') get_activation('''gelu_10''') get_activation('''gelu_fast''') get_activation('''gelu_new''') get_activation('''gelu_python''') get_activation('''gelu_pytorch_tanh''') get_activation('''linear''') get_activation('''mish''') get_activation('''quick_gelu''') get_activation('''relu''') get_activation('''sigmoid''') get_activation('''silu''') get_activation('''swish''') get_activation('''tanh''') with self.assertRaises(lowercase_): get_activation('''bogus''') with self.assertRaises(lowercase_): get_activation(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = get_activation('''gelu''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE_ : Dict = get_activation('''gelu''') self.assertEqual(acta.a , 1) with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : Any = acta.a
91
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar UpperCamelCase__ = TypeVar("""T""") class a__ ( Generic[T] ): def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = data __lowerCAmelCase = None def __str__( self ): """simple docstring""" return f"""{self.data}""" class a__ ( Generic[T] ): def __init__( self ): """simple docstring""" __lowerCAmelCase = None def __iter__( self ): """simple docstring""" __lowerCAmelCase = self.top while node: yield node.data __lowerCAmelCase = node.next def __str__( self ): """simple docstring""" return "->".join([str(_A ) for item in self] ) def __len__( self ): """simple docstring""" return len(tuple(iter(self ) ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.top is None def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = Node(_A ) if not self.is_empty(): __lowerCAmelCase = self.top __lowerCAmelCase = node def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.is_empty(): raise IndexError("pop from empty stack" ) assert isinstance(self.top , _A ) __lowerCAmelCase = self.top __lowerCAmelCase = self.top.next return pop_node.data def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.is_empty(): raise IndexError("peek from empty stack" ) assert self.top is not None return self.top.data def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = None if __name__ == "__main__": from doctest import testmod testmod()
92
'''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 ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\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 , *a , **a ): 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. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = 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. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = 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']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} 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`" ) UpperCamelCase__ = 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`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = 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." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments 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 , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = 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: UpperCamelCase__ = 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" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = 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. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "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: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "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 UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = 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 __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = 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: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase_ ) class lowerCAmelCase__ ( lowerCamelCase_ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowerCAmelCase_ = field(default='''summarization''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) lowerCAmelCase_ = Features({'''text''': Value('''string''' )} ) lowerCAmelCase_ = Features({'''summary''': Value('''string''' )} ) lowerCAmelCase_ = "text" lowerCAmelCase_ = "summary" @property def _snake_case ( self ): """simple docstring""" return {self.text_column: "text", self.summary_column: "summary"}
93
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar snake_case : Optional[int] = TypeVar('''T''') class _snake_case ( Generic[T] ): SCREAMING_SNAKE_CASE__ = 42 # Cache store of keys SCREAMING_SNAKE_CASE__ = 42 # References of the keys in cache SCREAMING_SNAKE_CASE__ = 10 # Maximum capacity of cache def __init__( self , _lowerCamelCase ): a :Optional[int] = deque() a :int = set() if not n: a :Dict = sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: a :int = n def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: a :str = self.dq_store.pop() self.key_reference.remove(_lowerCamelCase ) else: self.dq_store.remove(_lowerCamelCase ) self.dq_store.appendleft(_lowerCamelCase ) self.key_reference.add(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ): for k in self.dq_store: print(_lowerCamelCase ) def __repr__( self ): return F'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}''' if __name__ == "__main__": import doctest doctest.testmod() snake_case : LRUCache[str | int] = LRUCache(4) lru_cache.refer('''A''') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('''A''') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
94
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : str = { """post_extract_proj""": """feature_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.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str ): """simple docstring""" for attribute in key.split("." ): a__ : Tuple =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if weight_type is not None: a__ : Any =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).shape else: a__ : 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": a__ : int =value elif weight_type == "weight_g": a__ : Optional[Any] =value elif weight_type == "weight_v": a__ : int =value elif weight_type == "bias": a__ : Any =value else: a__ : Optional[int] =value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" a__ : List[str] =[] a__ : Dict =fairseq_model.state_dict() a__ : Union[str, Any] =hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): a__ : Optional[Any] =False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == "group" , ) a__ : List[str] =True else: for key, mapped_key in MAPPING.items(): a__ : str ="sew." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: a__ : Tuple =True if "*" in mapped_key: a__ : str =name.split(SCREAMING_SNAKE_CASE )[0].split("." )[-2] a__ : List[str] =mapped_key.replace("*" , SCREAMING_SNAKE_CASE ) if "weight_g" in name: a__ : List[str] ="weight_g" elif "weight_v" in name: a__ : Optional[int] ="weight_v" elif "weight" in name: a__ : Tuple ="weight" elif "bias" in name: a__ : Optional[int] ="bias" else: a__ : List[Any] =None set_recursively(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" a__ : int =full_name.split("conv_layers." )[-1] a__ : Union[str, Any] =name.split("." ) a__ : Tuple =int(items[0] ) a__ : Any =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.''' ) a__ : Any =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.''' ) a__ : 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." ) a__ : 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.''' ) a__ : str =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : Optional[int] =SEWConfig() if is_finetuned: a__ : Optional[Any] =model.wav_encoder.wav_model.cfg else: a__ : int =model.cfg a__ : Optional[Any] =fs_config.conv_bias a__ : List[Any] =eval(fs_config.conv_feature_layers ) a__ : Dict =[x[0] for x in conv_layers] a__ : str =[x[1] for x in conv_layers] a__ : Tuple =[x[2] for x in conv_layers] a__ : List[str] ="gelu" a__ : int ="layer" if fs_config.extractor_mode == "layer_norm" else "group" a__ : Optional[Any] =0.0 a__ : List[str] =fs_config.activation_fn.name a__ : Union[str, Any] =fs_config.encoder_embed_dim a__ : Any =0.0_2 a__ : Optional[Any] =fs_config.encoder_ffn_embed_dim a__ : Tuple =1e-5 a__ : Union[str, Any] =fs_config.encoder_layerdrop a__ : List[Any] =fs_config.encoder_attention_heads a__ : int =fs_config.conv_pos_groups a__ : int =fs_config.conv_pos a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =fs_config.encoder_layers a__ : Tuple =fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: a__ : Any =model.cfg a__ : Optional[Any] =fs_config.final_dropout a__ : Optional[int] =fs_config.layerdrop a__ : Optional[Any] =fs_config.activation_dropout a__ : Dict =fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 a__ : Tuple =fs_config.attention_dropout a__ : Tuple =fs_config.dropout_input a__ : List[str] =fs_config.dropout a__ : Optional[int] =fs_config.mask_channel_length a__ : List[str] =fs_config.mask_channel_prob a__ : Any =fs_config.mask_length a__ : Union[str, Any] =fs_config.mask_prob a__ : List[str] ="Wav2Vec2FeatureExtractor" a__ : List[str] ="Wav2Vec2CTCTokenizer" return config @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : str=None , SCREAMING_SNAKE_CASE : Dict=None , SCREAMING_SNAKE_CASE : List[str]=True ): """simple docstring""" if is_finetuned: a__ , a__ , a__ : Tuple =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: a__ , a__ , a__ : Dict =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: a__ : List[str] =SEWConfig.from_pretrained(SCREAMING_SNAKE_CASE ) else: a__ : Optional[int] =convert_config(model[0] , SCREAMING_SNAKE_CASE ) a__ : int =model[0].eval() a__ : List[str] =True if config.feat_extract_norm == "layer" else False a__ : Optional[int] =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , ) if is_finetuned: if dict_path: a__ : List[Any] =Dictionary.load(SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq a__ : Any =target_dict.pad_index a__ : Any =target_dict.bos_index a__ : List[Any] =target_dict.pad_index a__ : Dict =target_dict.bos_index a__ : Optional[int] =target_dict.eos_index a__ : Dict =len(target_dict.symbols ) a__ : List[str] =os.path.join(SCREAMING_SNAKE_CASE , "vocab.json" ) if not os.path.isdir(SCREAMING_SNAKE_CASE ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(SCREAMING_SNAKE_CASE ) ) return os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as vocab_handle: json.dump(target_dict.indices , SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =WavaVecaCTCTokenizer( SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=SCREAMING_SNAKE_CASE , ) a__ : List[Any] =WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =SEWForCTC(SCREAMING_SNAKE_CASE ) else: a__ : int =SEWModel(SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE ) recursively_load_weights(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCAmelCase : Tuple = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
95
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
"""simple docstring""" from __future__ import annotations import math from collections.abc import Callable def _snake_case ( lowercase__ , lowercase__ , lowercase__ , lowercase__ = 100 , ): _lowerCamelCase : Any = x_start _lowerCamelCase : Optional[int] = fnc(lowercase__ ) _lowerCamelCase : str = 0.0 for _ in range(lowercase__ ): # Approximates curve as a sequence of linear lines and sums their length _lowerCamelCase : str = (x_end - x_start) / steps + xa _lowerCamelCase : Any = fnc(lowercase__ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step _lowerCamelCase : List[Any] = xa _lowerCamelCase : Dict = fxa return length if __name__ == "__main__": def _snake_case ( lowercase__ ): return math.sin(10 * x ) print("""f(x) = sin(10 * x)""") print("""The length of the curve from x = -10 to x = 10 is:""") lowercase__ = 10 while i <= 10_0000: print(F"With {i} steps: {line_length(f, -10, 10, i)}") i *= 10
96
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig __snake_case = logging.get_logger(__name__) # General docstring __snake_case = '''RegNetConfig''' # Base docstring __snake_case = '''facebook/regnet-y-040''' __snake_case = [1, 1088, 7, 7] # Image classification docstring __snake_case = '''facebook/regnet-y-040''' __snake_case = '''tabby, tabby cat''' __snake_case = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ = 3 , UpperCamelCase_ = 1 , UpperCamelCase_ = 1 , UpperCamelCase_ = "relu" , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb UpperCamelCase__ :List[str] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) UpperCamelCase__ :Dict = tf.keras.layers.ConvaD( filters=UpperCamelCase_ , kernel_size=UpperCamelCase_ , strides=UpperCamelCase_ , padding='''VALID''' , groups=UpperCamelCase_ , use_bias=UpperCamelCase_ , name='''convolution''' , ) UpperCamelCase__ :Tuple = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) UpperCamelCase__ :Dict = ACTaFN[activation] if activation is not None else tf.identity def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = self.convolution(self.padding(UpperCamelCase_ ) ) UpperCamelCase__ :int = self.normalization(UpperCamelCase_ ) UpperCamelCase__ :Tuple = self.activation(UpperCamelCase_ ) return hidden_state class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Dict = config.num_channels UpperCamelCase__ :Union[str, Any] = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = shape_list(UpperCamelCase_ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) UpperCamelCase__ :int = tf.transpose(UpperCamelCase_ , perm=(0, 2, 3, 1) ) UpperCamelCase__ :Dict = self.embedder(UpperCamelCase_ ) return hidden_state class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ = 2 , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Optional[Any] = tf.keras.layers.ConvaD( filters=UpperCamelCase_ , kernel_size=1 , strides=UpperCamelCase_ , use_bias=UpperCamelCase_ , name='''convolution''' ) UpperCamelCase__ :Optional[int] = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = False ): '''simple docstring''' return self.normalization(self.convolution(UpperCamelCase_ ) , training=UpperCamelCase_ ) class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Tuple = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCamelCase_ , name='''pooler''' ) UpperCamelCase__ :str = [ tf.keras.layers.ConvaD(filters=UpperCamelCase_ , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=UpperCamelCase_ , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Any = self.pooler(UpperCamelCase_ ) for layer_module in self.attention: UpperCamelCase__ :Tuple = layer_module(UpperCamelCase_ ) UpperCamelCase__ :Tuple = hidden_state * pooled return hidden_state class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = 1 , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = in_channels != out_channels or stride != 1 UpperCamelCase__ :Any = max(1 , out_channels // config.groups_width ) UpperCamelCase__ :Optional[Any] = ( TFRegNetShortCut(UpperCamelCase_ , stride=UpperCamelCase_ , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. UpperCamelCase__ :Optional[Any] = [ TFRegNetConvLayer(UpperCamelCase_ , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( UpperCamelCase_ , stride=UpperCamelCase_ , groups=UpperCamelCase_ , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(UpperCamelCase_ , kernel_size=1 , activation=UpperCamelCase_ , name='''layer.2''' ), ] UpperCamelCase__ :List[Any] = ACTaFN[config.hidden_act] def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Any = hidden_state for layer_module in self.layers: UpperCamelCase__ :int = layer_module(UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = self.shortcut(UpperCamelCase_ ) hidden_state += residual UpperCamelCase__ :str = self.activation(UpperCamelCase_ ) return hidden_state class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = 1 , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Optional[int] = in_channels != out_channels or stride != 1 UpperCamelCase__ :int = max(1 , out_channels // config.groups_width ) UpperCamelCase__ :Tuple = ( TFRegNetShortCut(UpperCamelCase_ , stride=UpperCamelCase_ , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) UpperCamelCase__ :List[Any] = [ TFRegNetConvLayer(UpperCamelCase_ , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( UpperCamelCase_ , stride=UpperCamelCase_ , groups=UpperCamelCase_ , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(UpperCamelCase_ , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(UpperCamelCase_ , kernel_size=1 , activation=UpperCamelCase_ , name='''layer.3''' ), ] UpperCamelCase__ :int = ACTaFN[config.hidden_act] def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = hidden_state for layer_module in self.layers: UpperCamelCase__ :Optional[Any] = layer_module(UpperCamelCase_ ) UpperCamelCase__ :Optional[Any] = self.shortcut(UpperCamelCase_ ) hidden_state += residual UpperCamelCase__ :Dict = self.activation(UpperCamelCase_ ) return hidden_state class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = 2 , UpperCamelCase_ = 2 , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :List[str] = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer UpperCamelCase__ :Optional[Any] = [ # downsampling is done in the first layer with stride of 2 layer(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , stride=UpperCamelCase_ , name='''layers.0''' ), *[layer(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , name=F'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' for layer_module in self.layers: UpperCamelCase__ :List[str] = layer_module(UpperCamelCase_ ) return hidden_state class lowercase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :int = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCamelCase_ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) UpperCamelCase__ :int = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCamelCase_ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , depth=UpperCamelCase_ , name=F'''stages.{i+1}''' ) ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = False , UpperCamelCase_ = True ): '''simple docstring''' UpperCamelCase__ :Any = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: UpperCamelCase__ :List[Any] = hidden_states + (hidden_state,) UpperCamelCase__ :Optional[Any] = stage_module(UpperCamelCase_ ) if output_hidden_states: UpperCamelCase__ :Dict = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCamelCase_ , hidden_states=UpperCamelCase_ ) @keras_serializable class lowercase ( tf.keras.layers.Layer ): """simple docstring""" _a = RegNetConfig def __init__( self , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Any = config UpperCamelCase__ :Dict = TFRegNetEmbeddings(UpperCamelCase_ , name='''embedder''' ) UpperCamelCase__ :Any = TFRegNetEncoder(UpperCamelCase_ , name='''encoder''' ) UpperCamelCase__ :Union[str, Any] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCamelCase_ , name='''pooler''' ) @unpack_inputs def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = False , ): '''simple docstring''' UpperCamelCase__ :Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase__ :Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase__ :List[str] = self.embedder(UpperCamelCase_ , training=UpperCamelCase_ ) UpperCamelCase__ :Optional[int] = self.encoder( UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , return_dict=UpperCamelCase_ , training=UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = encoder_outputs[0] UpperCamelCase__ :str = self.pooler(UpperCamelCase_ ) # Change to NCHW output format have uniformity in the modules UpperCamelCase__ :Tuple = tf.transpose(UpperCamelCase_ , perm=(0, 3, 1, 2) ) UpperCamelCase__ :List[str] = tf.transpose(UpperCamelCase_ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: UpperCamelCase__ :Union[str, Any] = tuple([tf.transpose(UpperCamelCase_ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCamelCase_ , pooler_output=UpperCamelCase_ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class lowercase ( A__ ): """simple docstring""" _a = RegNetConfig _a = 'regnet' _a = 'pixel_values' @property def lowerCAmelCase__ ( self ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} __snake_case = R''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' __snake_case = R''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , A__ , ) class lowercase ( A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' super().__init__(UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase__ :str = TFRegNetMainLayer(UpperCamelCase_ , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCamelCase_ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCamelCase_ , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_=False , ): '''simple docstring''' UpperCamelCase__ :str = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase__ :Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase__ :Tuple = self.regnet( pixel_values=UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , return_dict=UpperCamelCase_ , training=UpperCamelCase_ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , A__ , ) class lowercase ( A__ , A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' super().__init__(UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase__ :List[str] = config.num_labels UpperCamelCase__ :Dict = TFRegNetMainLayer(UpperCamelCase_ , name='''regnet''' ) # classification head UpperCamelCase__ :str = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCamelCase_ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCamelCase_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowerCAmelCase__ ( self , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_=False , ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase__ :List[Any] = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase__ :List[str] = self.regnet( UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , return_dict=UpperCamelCase_ , training=UpperCamelCase_ ) UpperCamelCase__ :str = outputs.pooler_output if return_dict else outputs[1] UpperCamelCase__ :Tuple = self.classifier[0](UpperCamelCase_ ) UpperCamelCase__ :Optional[int] = self.classifier[1](UpperCamelCase_ ) UpperCamelCase__ :Dict = None if labels is None else self.hf_compute_loss(labels=UpperCamelCase_ , logits=UpperCamelCase_ ) if not return_dict: UpperCamelCase__ :Optional[int] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCamelCase_ , logits=UpperCamelCase_ , hidden_states=outputs.hidden_states )
97
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging lowerCAmelCase__ : List[Any] = logging.get_logger(__name__) class snake_case ( __UpperCAmelCase ): """simple docstring""" def __init__( self : List[str] ,lowerCamelCase__ : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): super().__init__() UpperCAmelCase__ = nn.ModuleList(lowerCamelCase__ ) def __lowerCAmelCase ( self : Tuple ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : Union[torch.Tensor, float, int] ,lowerCamelCase__ : torch.Tensor ,lowerCamelCase__ : List[torch.tensor] ,lowerCamelCase__ : List[float] ,lowerCamelCase__ : Optional[torch.Tensor] = None ,lowerCamelCase__ : Optional[torch.Tensor] = None ,lowerCamelCase__ : Optional[torch.Tensor] = None ,lowerCamelCase__ : Optional[Dict[str, Any]] = None ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : bool = True ,): for i, (image, scale, controlnet) in enumerate(zip(lowerCamelCase__ ,lowerCamelCase__ ,self.nets ) ): UpperCAmelCase__ , UpperCAmelCase__ = controlnet( lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,) # merge samples if i == 0: UpperCAmelCase__ , UpperCAmelCase__ = down_samples, mid_sample else: UpperCAmelCase__ = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(lowerCamelCase__ ,lowerCamelCase__ ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def __lowerCAmelCase ( self : Union[str, Any] ,lowerCamelCase__ : Union[str, os.PathLike] ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : Callable = None ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : Optional[str] = None ,): UpperCAmelCase__ = 0 UpperCAmelCase__ = save_directory for controlnet in self.nets: controlnet.save_pretrained( lowerCamelCase__ ,is_main_process=lowerCamelCase__ ,save_function=lowerCamelCase__ ,safe_serialization=lowerCamelCase__ ,variant=lowerCamelCase__ ,) idx += 1 UpperCAmelCase__ = model_path_to_save + f'''_{idx}''' @classmethod def __lowerCAmelCase ( cls : str ,lowerCamelCase__ : Optional[Union[str, os.PathLike]] ,**lowerCamelCase__ : str ): UpperCAmelCase__ = 0 UpperCAmelCase__ = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... UpperCAmelCase__ = pretrained_model_path while os.path.isdir(lowerCamelCase__ ): UpperCAmelCase__ = ControlNetModel.from_pretrained(lowerCamelCase__ ,**lowerCamelCase__ ) controlnets.append(lowerCamelCase__ ) idx += 1 UpperCAmelCase__ = pretrained_model_path + f'''_{idx}''' logger.info(f'''{len(lowerCamelCase__ )} controlnets loaded from {pretrained_model_path}.''' ) if len(lowerCamelCase__ ) == 0: raise ValueError( f'''No ControlNets found under {os.path.dirname(lowerCamelCase__ )}. Expected at least {pretrained_model_path + "_0"}.''' ) return cls(lowerCamelCase__ )
98
'''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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = 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: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
def A_ ( A__ ) -> list: a__ : Dict = len(A__ ) for _ in range(A__ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: a__ , a__ : Any = arr[i + 1], arr[i] return arr if __name__ == "__main__": lowercase : Optional[int] = list(range(1_0, 0, -1)) print(F"""Original: {arr}. Sorted: {odd_even_transposition(arr)}""")
99
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = 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 __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" , [ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(UpperCamelCase_ , i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = _distribute_shards(**UpperCamelCase_ ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" , [ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] , ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = _split_gen_kwargs(UpperCamelCase_ , UpperCamelCase_ ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" , [ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] , ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): if expected is RuntimeError: with pytest.raises(UpperCamelCase_ ): _number_of_shards_in_gen_kwargs(UpperCamelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(UpperCamelCase_ ) assert out == expected
100
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy lowercase__ :Dict = logging.getLogger(__name__) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , ): '''simple docstring''' lowercase = bnb_quantization_config.load_in_abit lowercase = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( '''You have a version of `bitsandbytes` that is not compatible with 8bit quantization,''' ''' make sure you have the latest version of `bitsandbytes` installed.''' ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( '''You have a version of `bitsandbytes` that is not compatible with 4bit quantization,''' '''make sure you have the latest version of `bitsandbytes` installed.''' ) lowercase = [] # custom device map if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and len(device_map.keys() ) > 1: lowercase = [key for key, value in device_map.items() if value in ['''disk''', '''cpu''']] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowercase = get_keys_to_not_convert(lowerCAmelCase__ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(lowerCAmelCase__ ) lowercase = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowercase = [] lowercase = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(lowerCAmelCase__ ) # compatibility with peft lowercase = load_in_abit lowercase = load_in_abit lowercase = get_parameter_device(lowerCAmelCase__ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( '''It is not recommended to quantize a loaded model. ''' '''The model should be instantiated under the `init_empty_weights` context manager.''' ) lowercase = replace_with_bnb_layers(lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ ) # convert param to the right dtype lowercase = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowercase = name.replace('''.weight''' , '''''' ).replace('''.bias''' , '''''' ) lowercase = getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(lowerCAmelCase__ ): param.to(lowerCAmelCase__ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info( f'The model device type is {model_device.type}. However, cuda is needed for quantization.' '''We move the model to cuda.''' ) return model elif weights_location is None: raise RuntimeError( f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' ) else: with init_empty_weights(): lowercase = replace_with_bnb_layers( lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ ) lowercase = get_quantized_model_device_map( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , max_memory=lowerCAmelCase__ , no_split_module_classes=lowerCAmelCase__ , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowercase = True lowercase = any(x in list(device_map.values() ) for x in ['''cpu''', '''disk'''] ) load_checkpoint_in_model( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , dtype=bnb_quantization_config.torch_dtype , offload_folder=lowerCAmelCase__ , offload_state_dict=lowerCAmelCase__ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(lowerCAmelCase__ , device_map=lowerCAmelCase__ , offload_dir=lowerCAmelCase__ ) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None ): '''simple docstring''' if device_map is None: if torch.cuda.is_available(): lowercase = {'''''': torch.cuda.current_device()} else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info('''The device_map was not initialized.''' '''Setting device_map to `{\'\':torch.cuda.current_device()}`.''' ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( '''If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or ''' '''\'sequential\'.''' ) lowercase = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowercase = {} lowercase = special_dtypes lowercase = no_split_module_classes lowercase = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowercase = get_balanced_memory( lowerCAmelCase__ , low_zero=(device_map == '''balanced_low_0''') , max_memory=lowerCAmelCase__ , **lowerCAmelCase__ , ) lowercase = max_memory lowercase = infer_auto_device_map(lowerCAmelCase__ , **lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): # check if don't have any quantized module on the cpu lowercase = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowercase = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( ''' Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. ''' ) else: logger.info( '''Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit''' ) del device_map_without_some_modules return device_map def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None ): '''simple docstring''' if modules_to_not_convert is None: lowercase = [] lowercase , lowercase = _replace_with_bnb_layers( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None , ): '''simple docstring''' lowercase = False for name, module in model.named_children(): if current_key_name is None: lowercase = [] current_key_name.append(lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowercase = '''.'''.join(lowerCAmelCase__ ) lowercase = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowercase = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowercase = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=lowerCAmelCase__ , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowercase = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError('''load_in_8bit and load_in_4bit can\'t be both False''' ) lowercase = module.weight.data if module.bias is not None: lowercase = module.bias.data bnb_module.requires_grad_(lowerCAmelCase__ ) setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) lowercase = True if len(list(module.children() ) ) > 0: lowercase , lowercase = _replace_with_bnb_layers( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) lowercase = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' # Create a copy of the model with init_empty_weights(): lowercase = deepcopy(lowerCAmelCase__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowercase = find_tied_parameters(lowerCAmelCase__ ) # For compatibility with Accelerate < 0.18 if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowercase = sum(lowerCAmelCase__ , [] ) lowercase = len(lowerCAmelCase__ ) > 0 # Check if it is a base model lowercase = False if hasattr(lowerCAmelCase__ , '''base_model_prefix''' ): lowercase = not hasattr(lowerCAmelCase__ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowercase = list(model.named_children() ) lowercase = [list_modules[-1][0]] # add last module together with tied weights lowercase = set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) lowercase = list(set(lowerCAmelCase__ ) ) + list(lowerCAmelCase__ ) # remove ".weight" from the keys lowercase = ['''.weight''', '''.bias'''] lowercase = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowercase = name.replace(lowerCAmelCase__ , '''''' ) filtered_module_names.append(lowerCAmelCase__ ) return filtered_module_names def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' for m in model.modules(): if isinstance(lowerCAmelCase__ , bnb.nn.Linearabit ): return True return False def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' return next(parameter.parameters() ).device def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , 0 , dtype=lowerCAmelCase__ , value=lowerCAmelCase__ ) lowercase = param_name lowercase = model if "." in tensor_name: lowercase = tensor_name.split('''.''' ) for split in splits[:-1]: lowercase = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) if new_module is None: raise ValueError(f'{module} has no attribute {split}.' ) lowercase = new_module lowercase = splits[-1] # offload weights lowercase = False offload_weight(module._parameters[tensor_name] , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ ) if hasattr(module._parameters[tensor_name] , '''SCB''' ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace('''weight''' , '''SCB''' ) , lowerCAmelCase__ , index=lowerCAmelCase__ , ) else: offload_weight(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ ) offload_weight(lowerCAmelCase__ , param_name.replace('''weight''' , '''SCB''' ) , lowerCAmelCase__ , index=lowerCAmelCase__ ) set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , '''meta''' , dtype=lowerCAmelCase__ , value=torch.empty(*param.size() ) )
101
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
"""simple docstring""" import argparse import os import re import packaging.version SCREAMING_SNAKE_CASE : Optional[int] = """examples/""" SCREAMING_SNAKE_CASE : Optional[Any] = { """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""), """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } SCREAMING_SNAKE_CASE : Tuple = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } SCREAMING_SNAKE_CASE : Optional[int] = """README.md""" def lowercase ( _snake_case : str , _snake_case : int , _snake_case : List[str] ) ->Tuple: """simple docstring""" with open(_snake_case , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __snake_case : str = f.read() __snake_case , __snake_case : Optional[Any] = REPLACE_PATTERNS[pattern] __snake_case : List[str] = replace.replace('''VERSION''' , _snake_case ) __snake_case : Any = re_pattern.sub(_snake_case , _snake_case ) with open(_snake_case , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(_snake_case ) def lowercase ( _snake_case : Any ) ->Tuple: """simple docstring""" for folder, directories, fnames in os.walk(_snake_case ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(_snake_case , _snake_case ) , _snake_case , pattern='''examples''' ) def lowercase ( _snake_case : Optional[int] , _snake_case : str=False ) ->str: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_snake_case , _snake_case , _snake_case ) if not patch: update_version_in_examples(_snake_case ) def lowercase ( ) ->List[str]: """simple docstring""" __snake_case : List[Any] = '''🤗 Transformers currently provides the following architectures''' __snake_case : Optional[int] = '''1. Want to contribute a new model?''' with open(_snake_case , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __snake_case : List[Any] = f.readlines() # Find the start of the list. __snake_case : List[str] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __snake_case : Any = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): __snake_case : str = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(_snake_case , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(_snake_case ) def lowercase ( ) ->List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] , '''r''' ) as f: __snake_case : Dict = f.read() __snake_case : Any = REPLACE_PATTERNS['''init'''][0].search(_snake_case ).groups()[0] return packaging.version.parse(_snake_case ) def lowercase ( _snake_case : List[str]=False ) ->str: """simple docstring""" __snake_case : List[Any] = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: __snake_case : Union[str, Any] = default_version.base_version elif patch: __snake_case : Union[str, Any] = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __snake_case : List[Any] = f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __snake_case : str = input(f"""Which version are you releasing? [{default_version}]""" ) if len(_snake_case ) == 0: __snake_case : str = default_version print(f"""Updating version to {version}.""" ) global_version_update(_snake_case , patch=_snake_case ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def lowercase ( ) ->List[Any]: """simple docstring""" __snake_case : Tuple = get_version() __snake_case : str = f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __snake_case : int = current_version.base_version # Check with the user we got that right. __snake_case : Tuple = input(f"""Which version are we developing now? [{dev_version}]""" ) if len(_snake_case ) == 0: __snake_case : Any = dev_version print(f"""Updating version to {version}.""" ) global_version_update(_snake_case ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": SCREAMING_SNAKE_CASE : Dict = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") SCREAMING_SNAKE_CASE : Any = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
102
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def UpperCamelCase( __UpperCamelCase : Union[str, Any] ): lowerCAmelCase_ : Any = 384 if "tiny" in model_name: lowerCAmelCase_ : Tuple = [3, 3, 9, 3] lowerCAmelCase_ : List[str] = [96, 192, 384, 768] if "small" in model_name: lowerCAmelCase_ : List[Any] = [3, 3, 27, 3] lowerCAmelCase_ : List[str] = [96, 192, 384, 768] if "base" in model_name: lowerCAmelCase_ : Optional[int] = [3, 3, 27, 3] lowerCAmelCase_ : List[str] = [128, 256, 512, 1024] lowerCAmelCase_ : int = 512 if "large" in model_name: lowerCAmelCase_ : List[str] = [3, 3, 27, 3] lowerCAmelCase_ : int = [192, 384, 768, 1536] lowerCAmelCase_ : List[Any] = 768 if "xlarge" in model_name: lowerCAmelCase_ : Optional[Any] = [3, 3, 27, 3] lowerCAmelCase_ : Optional[int] = [256, 512, 1024, 2048] lowerCAmelCase_ : Optional[Any] = 1024 # set label information lowerCAmelCase_ : Tuple = 150 lowerCAmelCase_ : Optional[int] = '''huggingface/label-files''' lowerCAmelCase_ : str = '''ade20k-id2label.json''' lowerCAmelCase_ : List[str] = json.load(open(hf_hub_download(__UpperCamelCase ,__UpperCamelCase ,repo_type='''dataset''' ) ,'''r''' ) ) lowerCAmelCase_ : Any = {int(__UpperCamelCase ): v for k, v in idalabel.items()} lowerCAmelCase_ : Optional[int] = {v: k for k, v in idalabel.items()} lowerCAmelCase_ : Dict = ConvNextConfig( depths=__UpperCamelCase ,hidden_sizes=__UpperCamelCase ,out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) lowerCAmelCase_ : List[Any] = UperNetConfig( backbone_config=__UpperCamelCase ,auxiliary_in_channels=__UpperCamelCase ,num_labels=__UpperCamelCase ,idalabel=__UpperCamelCase ,labelaid=__UpperCamelCase ,) return config def UpperCamelCase( __UpperCamelCase : List[Any] ): lowerCAmelCase_ : List[str] = [] # fmt: off # stem rename_keys.append(('''backbone.downsample_layers.0.0.weight''', '''backbone.embeddings.patch_embeddings.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.0.bias''', '''backbone.embeddings.patch_embeddings.bias''') ) rename_keys.append(('''backbone.downsample_layers.0.1.weight''', '''backbone.embeddings.layernorm.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.1.bias''', '''backbone.embeddings.layernorm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"""backbone.stages.{i}.{j}.gamma""", f"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.norm.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.norm.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") ) if i > 0: rename_keys.append((f"""backbone.downsample_layers.{i}.0.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.0.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.1.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.1.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""") ) rename_keys.append((f"""backbone.norm{i}.weight""", f"""backbone.hidden_states_norms.stage{i+1}.weight""") ) rename_keys.append((f"""backbone.norm{i}.bias""", f"""backbone.hidden_states_norms.stage{i+1}.bias""") ) # decode head rename_keys.extend( [ ('''decode_head.conv_seg.weight''', '''decode_head.classifier.weight'''), ('''decode_head.conv_seg.bias''', '''decode_head.classifier.bias'''), ('''auxiliary_head.conv_seg.weight''', '''auxiliary_head.classifier.weight'''), ('''auxiliary_head.conv_seg.bias''', '''auxiliary_head.classifier.bias'''), ] ) # fmt: on return rename_keys def UpperCamelCase( __UpperCamelCase : int ,__UpperCamelCase : Optional[Any] ,__UpperCamelCase : Tuple ): lowerCAmelCase_ : Any = dct.pop(__UpperCamelCase ) lowerCAmelCase_ : Tuple = val def UpperCamelCase( __UpperCamelCase : Optional[int] ,__UpperCamelCase : int ,__UpperCamelCase : Dict ): lowerCAmelCase_ : List[Any] = { '''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''', '''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''', '''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''', '''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''', '''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''', } lowerCAmelCase_ : str = model_name_to_url[model_name] lowerCAmelCase_ : str = torch.hub.load_state_dict_from_url(__UpperCamelCase ,map_location='''cpu''' )['''state_dict'''] lowerCAmelCase_ : Optional[int] = get_upernet_config(__UpperCamelCase ) lowerCAmelCase_ : Any = UperNetForSemanticSegmentation(__UpperCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): lowerCAmelCase_ : Dict = state_dict.pop(__UpperCamelCase ) if "bn" in key: lowerCAmelCase_ : List[str] = key.replace('''bn''' ,'''batch_norm''' ) lowerCAmelCase_ : Tuple = val # rename keys lowerCAmelCase_ : str = create_rename_keys(__UpperCamelCase ) for src, dest in rename_keys: rename_key(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) # verify on image lowerCAmelCase_ : int = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' lowerCAmelCase_ : Tuple = Image.open(requests.get(__UpperCamelCase ,stream=__UpperCamelCase ).raw ).convert('''RGB''' ) lowerCAmelCase_ : Dict = SegformerImageProcessor() lowerCAmelCase_ : Any = processor(__UpperCamelCase ,return_tensors='''pt''' ).pixel_values with torch.no_grad(): lowerCAmelCase_ : str = model(__UpperCamelCase ) if model_name == "upernet-convnext-tiny": lowerCAmelCase_ : List[str] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ) elif model_name == "upernet-convnext-small": lowerCAmelCase_ : Union[str, Any] = torch.tensor( [[-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.7_6_3_8, -8.7_6_3_8, -8.6_2_4_0]] ) elif model_name == "upernet-convnext-base": lowerCAmelCase_ : Dict = torch.tensor( [[-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.7_6_6_9, -8.7_6_6_9, -8.6_0_2_1]] ) elif model_name == "upernet-convnext-large": lowerCAmelCase_ : Optional[Any] = torch.tensor( [[-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_3_1_0, -8.6_3_1_0, -8.5_9_6_4]] ) elif model_name == "upernet-convnext-xlarge": lowerCAmelCase_ : Dict = torch.tensor( [[-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_3_7_9, -8.4_3_7_9, -8.3_4_1_2]] ) print('''Logits:''' ,outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] ,__UpperCamelCase ,atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(__UpperCamelCase ) if push_to_hub: print(f"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(f"""openmmlab/{model_name}""" ) processor.push_to_hub(f"""openmmlab/{model_name}""" ) if __name__ == "__main__": A__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''upernet-convnext-tiny''', type=str, choices=[F'''upernet-convnext-{size}''' for size in ['''tiny''', '''small''', '''base''', '''large''', '''xlarge''']], help='''Name of the ConvNext UperNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) A__ : int = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
103
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
104
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
"""simple docstring""" 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 __UpperCamelCase ( unittest.TestCase ): @cached_property def __a ( self ) -> Optional[int]: a : Optional[int] = tempfile.mkdtemp() return TatoebaConverter(save_dir=lowerCAmelCase__ ) @slow def __a ( self ) -> str: self.resolver.convert_models(["heb-eng"] ) @slow def __a ( self ) -> str: a, a : str = self.resolver.write_model_card("opus-mt-he-en" , dry_run=lowerCAmelCase__ ) assert mmeta["long_pair"] == "heb-eng"
105
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = ["image_processor", "tokenizer"] lowercase__ = "ViltImageProcessor" lowercase__ = ("BertTokenizer", "BertTokenizerFast") def __init__( self : List[Any] ,lowercase_ : int=None ,lowercase_ : int=None ,**lowercase_ : Union[str, Any] ): lowerCAmelCase__ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' ,lowercase_ ,) lowerCAmelCase__ : Optional[Any] = kwargs.pop('''feature_extractor''' ) lowerCAmelCase__ : List[str] = 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__(lowercase_ ,lowercase_ ) lowerCAmelCase__ : Optional[Any] = self.image_processor def __call__( self : Tuple ,lowercase_ : Tuple ,lowercase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,lowercase_ : bool = True ,lowercase_ : Union[bool, str, PaddingStrategy] = False ,lowercase_ : Union[bool, str, TruncationStrategy] = None ,lowercase_ : Optional[int] = None ,lowercase_ : int = 0 ,lowercase_ : Optional[int] = None ,lowercase_ : Optional[bool] = None ,lowercase_ : Optional[bool] = None ,lowercase_ : bool = False ,lowercase_ : bool = False ,lowercase_ : bool = False ,lowercase_ : bool = False ,lowercase_ : bool = True ,lowercase_ : Optional[Union[str, TensorType]] = None ,**lowercase_ : List[str] ,): lowerCAmelCase__ : List[Any] = self.tokenizer( text=lowercase_ ,add_special_tokens=lowercase_ ,padding=lowercase_ ,truncation=lowercase_ ,max_length=lowercase_ ,stride=lowercase_ ,pad_to_multiple_of=lowercase_ ,return_token_type_ids=lowercase_ ,return_attention_mask=lowercase_ ,return_overflowing_tokens=lowercase_ ,return_special_tokens_mask=lowercase_ ,return_offsets_mapping=lowercase_ ,return_length=lowercase_ ,verbose=lowercase_ ,return_tensors=lowercase_ ,**lowercase_ ,) # add pixel_values + pixel_mask lowerCAmelCase__ : Optional[Any] = self.image_processor(lowercase_ ,return_tensors=lowercase_ ) encoding.update(lowercase_ ) return encoding def __lowerCAmelCase ( self : Tuple ,*lowercase_ : Any ,**lowercase_ : List[str] ): return self.tokenizer.batch_decode(*lowercase_ ,**lowercase_ ) def __lowerCAmelCase ( self : Tuple ,*lowercase_ : str ,**lowercase_ : Tuple ): return self.tokenizer.decode(*lowercase_ ,**lowercase_ ) @property def __lowerCAmelCase ( self : int ): lowerCAmelCase__ : Tuple = self.tokenizer.model_input_names lowerCAmelCase__ : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : Union[str, Any] ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,lowercase_ ,) return self.image_processor_class @property def __lowerCAmelCase ( self : int ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' ,lowercase_ ,) return self.image_processor
106
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ (unittest.TestCase ): """simple docstring""" def __init__( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple=3 , __lowerCamelCase : List[str]=32 , __lowerCamelCase : str=3 , __lowerCamelCase : Optional[int]=10 , __lowerCamelCase : str=[10, 20, 30, 40] , __lowerCamelCase : Tuple=[1, 1, 2, 1] , __lowerCamelCase : str=True , __lowerCamelCase : List[str]=True , __lowerCamelCase : Optional[int]="relu" , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Optional[int]=None , ) -> Any: 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(__lowerCamelCase ) def __UpperCAmelCase ( self : List[str] ) -> Dict: a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = self.get_config() return config, pixel_values def __UpperCAmelCase ( self : int ) -> Tuple: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any ) -> Dict: a = FlaxRegNetModel(config=__lowerCamelCase ) a = model(__lowerCamelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] ) -> Optional[int]: a = self.num_labels a = FlaxRegNetForImageClassification(config=__lowerCamelCase ) a = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self : int ) -> List[Any]: a = self.prepare_config_and_inputs() a , a = config_and_inputs a = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class snake_case__ (_UpperCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () SCREAMING_SNAKE_CASE_ : str = False SCREAMING_SNAKE_CASE_ : Optional[Any] = False SCREAMING_SNAKE_CASE_ : List[str] = False def __UpperCAmelCase ( self : Any ) -> None: a = FlaxRegNetModelTester(self ) a = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def __UpperCAmelCase ( self : int ) -> Dict: 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 __UpperCAmelCase ( self : str ) -> Optional[Any]: return def __UpperCAmelCase ( self : Tuple ) -> List[Any]: a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def __UpperCAmelCase ( self : List[Any] ) -> Tuple: a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @unittest.skip(reason="RegNet does not use inputs_embeds" ) def __UpperCAmelCase ( self : Optional[Any] ) -> Tuple: pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def __UpperCAmelCase ( self : Tuple ) -> Dict: pass def __UpperCAmelCase ( self : Dict ) -> Optional[int]: a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__lowerCamelCase ) a = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def __UpperCAmelCase ( self : Dict ) -> Tuple: def check_hidden_states_output(__lowerCamelCase : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : List[str] ): a = model_class(__lowerCamelCase ) a = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) , expected_num_stages + 1 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def __UpperCAmelCase ( self : Dict ) -> str: 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(__lowerCamelCase , __lowerCamelCase ) a = model_class(__lowerCamelCase ) @jax.jit def model_jitted(__lowerCamelCase : List[str] , **__lowerCamelCase : List[Any] ): return model(pixel_values=__lowerCamelCase , **__lowerCamelCase ) with self.subTest("JIT Enabled" ): a = model_jitted(**__lowerCamelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): a = model_jitted(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def __magic_name__ ( ): '''simple docstring''' a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_flax class snake_case__ (unittest.TestCase ): """simple docstring""" @cached_property def __UpperCAmelCase ( self : Any ) -> List[str]: return AutoImageProcessor.from_pretrained("facebook/regnet-y-040" ) if is_vision_available() else None @slow def __UpperCAmelCase ( self : List[Any] ) -> List[str]: a = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040" ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__lowerCamelCase , return_tensors="np" ) a = model(**__lowerCamelCase ) # verify the logits a = (1, 10_00) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) a = jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
107
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase__ = { '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
108
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): 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 , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
"""simple docstring""" import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) A: str = logging.getLogger(__name__) def _snake_case ( UpperCamelCase : Dict , UpperCamelCase : Optional[Any] ): UpperCAmelCase : List[Any] = np.argmax(UpperCamelCase , axis=1 ) return np.sum(outputs == labels ) def _snake_case ( UpperCamelCase : str ): with open(UpperCamelCase , encoding="""utf_8""" ) as f: UpperCAmelCase : int = csv.reader(UpperCamelCase ) UpperCAmelCase : str = [] next(UpperCamelCase ) # skip the first line for line in tqdm(UpperCamelCase ): output.append((""" """.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _snake_case ( UpperCamelCase : Optional[int] , UpperCamelCase : List[Any] , UpperCamelCase : Tuple , UpperCamelCase : Dict , UpperCamelCase : List[str] , UpperCamelCase : str ): UpperCAmelCase : Optional[Any] = [] for dataset in encoded_datasets: UpperCAmelCase : List[Any] = len(UpperCamelCase ) UpperCAmelCase : List[Any] = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) UpperCAmelCase : int = np.zeros((n_batch, 2) , dtype=np.intaa ) UpperCAmelCase : List[str] = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) UpperCAmelCase : List[str] = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(UpperCamelCase ): UpperCAmelCase : Optional[int] = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] UpperCAmelCase : List[Any] = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] UpperCAmelCase : str = with_conta UpperCAmelCase : Union[str, Any] = with_conta UpperCAmelCase : Optional[int] = len(UpperCamelCase ) - 1 UpperCAmelCase : List[str] = len(UpperCamelCase ) - 1 UpperCAmelCase : Union[str, Any] = with_conta UpperCAmelCase : Dict = with_conta UpperCAmelCase : Dict = mc_label UpperCAmelCase : Union[str, Any] = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(UpperCamelCase ) for t in all_inputs ) ) return tensor_datasets def _snake_case ( ): UpperCAmelCase : str = argparse.ArgumentParser() parser.add_argument("""--model_name""" , type=UpperCamelCase , default="""openai-gpt""" , help="""pretrained model name""" ) parser.add_argument("""--do_train""" , action="""store_true""" , help="""Whether to run training.""" ) parser.add_argument("""--do_eval""" , action="""store_true""" , help="""Whether to run eval on the dev set.""" ) parser.add_argument( """--output_dir""" , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help="""The output directory where the model predictions and checkpoints will be written.""" , ) parser.add_argument("""--train_dataset""" , type=UpperCamelCase , default="""""" ) parser.add_argument("""--eval_dataset""" , type=UpperCamelCase , default="""""" ) parser.add_argument("""--seed""" , type=UpperCamelCase , default=42 ) parser.add_argument("""--num_train_epochs""" , type=UpperCamelCase , default=3 ) parser.add_argument("""--train_batch_size""" , type=UpperCamelCase , default=8 ) parser.add_argument("""--eval_batch_size""" , type=UpperCamelCase , default=16 ) parser.add_argument("""--adam_epsilon""" , default=1e-8 , type=UpperCamelCase , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , type=UpperCamelCase , default=1 ) parser.add_argument( """--max_steps""" , default=-1 , type=UpperCamelCase , help=( """If > 0: set total number of training steps to perform. Override num_train_epochs.""" ) , ) parser.add_argument( """--gradient_accumulation_steps""" , type=UpperCamelCase , default=1 , help="""Number of updates steps to accumulate before performing a backward/update pass.""" , ) parser.add_argument("""--learning_rate""" , type=UpperCamelCase , default=6.2_5e-5 ) parser.add_argument("""--warmup_steps""" , default=0 , type=UpperCamelCase , help="""Linear warmup over warmup_steps.""" ) parser.add_argument("""--lr_schedule""" , type=UpperCamelCase , default="""warmup_linear""" ) parser.add_argument("""--weight_decay""" , type=UpperCamelCase , default=0.01 ) parser.add_argument("""--lm_coef""" , type=UpperCamelCase , default=0.9 ) parser.add_argument("""--n_valid""" , type=UpperCamelCase , default=374 ) parser.add_argument("""--server_ip""" , type=UpperCamelCase , default="""""" , help="""Can be used for distant debugging.""" ) parser.add_argument("""--server_port""" , type=UpperCamelCase , default="""""" , help="""Can be used for distant debugging.""" ) UpperCAmelCase : Tuple = parser.parse_args() print(UpperCamelCase ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("""Waiting for debugger attach""" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=UpperCamelCase ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) UpperCAmelCase : Union[str, Any] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) UpperCAmelCase : Tuple = torch.cuda.device_count() logger.info("""device: {}, n_gpu {}""".format(UpperCamelCase , UpperCamelCase ) ) if not args.do_train and not args.do_eval: raise ValueError("""At least one of `do_train` or `do_eval` must be True.""" ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset UpperCAmelCase : Optional[int] = ["""_start_""", """_delimiter_""", """_classify_"""] UpperCAmelCase : Tuple = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(UpperCamelCase ) UpperCAmelCase : str = tokenizer.convert_tokens_to_ids(UpperCamelCase ) UpperCAmelCase : List[Any] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(UpperCamelCase ) ) model.to(UpperCamelCase ) # Load and encode the datasets def tokenize_and_encode(UpperCamelCase : Dict ): if isinstance(UpperCamelCase , UpperCamelCase ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(UpperCamelCase ) ) elif isinstance(UpperCamelCase , UpperCamelCase ): return obj return [tokenize_and_encode(UpperCamelCase ) for o in obj] logger.info("""Encoding dataset...""" ) UpperCAmelCase : Optional[Any] = load_rocstories_dataset(args.train_dataset ) UpperCAmelCase : Dict = load_rocstories_dataset(args.eval_dataset ) UpperCAmelCase : Dict = (train_dataset, eval_dataset) UpperCAmelCase : Dict = tokenize_and_encode(UpperCamelCase ) # Compute the max input length for the Transformer UpperCAmelCase : List[Any] = model.config.n_positions // 2 - 2 UpperCAmelCase : str = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) UpperCAmelCase : Tuple = min(UpperCamelCase , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders UpperCAmelCase : Tuple = pre_process_datasets(UpperCamelCase , UpperCamelCase , UpperCamelCase , *UpperCamelCase ) UpperCAmelCase , UpperCAmelCase : Optional[int] = tensor_datasets[0], tensor_datasets[1] UpperCAmelCase : Optional[int] = TensorDataset(*UpperCamelCase ) UpperCAmelCase : Optional[int] = RandomSampler(UpperCamelCase ) UpperCAmelCase : Optional[int] = DataLoader(UpperCamelCase , sampler=UpperCamelCase , batch_size=args.train_batch_size ) UpperCAmelCase : Union[str, Any] = TensorDataset(*UpperCamelCase ) UpperCAmelCase : Any = SequentialSampler(UpperCamelCase ) UpperCAmelCase : Optional[Any] = DataLoader(UpperCamelCase , sampler=UpperCamelCase , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: UpperCAmelCase : str = args.max_steps UpperCAmelCase : Union[str, Any] = args.max_steps // (len(UpperCamelCase ) // args.gradient_accumulation_steps) + 1 else: UpperCAmelCase : Optional[int] = len(UpperCamelCase ) // args.gradient_accumulation_steps * args.num_train_epochs UpperCAmelCase : Any = list(model.named_parameters() ) UpperCAmelCase : Optional[int] = ["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""] UpperCAmelCase : Tuple = [ { """params""": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], """weight_decay""": args.weight_decay, }, {"""params""": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], """weight_decay""": 0.0}, ] UpperCAmelCase : Dict = AdamW(UpperCamelCase , lr=args.learning_rate , eps=args.adam_epsilon ) UpperCAmelCase : Optional[int] = get_linear_schedule_with_warmup( UpperCamelCase , num_warmup_steps=args.warmup_steps , num_training_steps=UpperCamelCase ) if args.do_train: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Any = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="""Epoch""" ): UpperCAmelCase : List[Any] = 0 UpperCAmelCase : Tuple = 0 UpperCAmelCase : str = tqdm(UpperCamelCase , desc="""Training""" ) for step, batch in enumerate(UpperCamelCase ): UpperCAmelCase : int = tuple(t.to(UpperCamelCase ) for t in batch ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : int = batch UpperCAmelCase : List[str] = model(UpperCamelCase , mc_token_ids=UpperCamelCase , lm_labels=UpperCamelCase , mc_labels=UpperCamelCase ) UpperCAmelCase : Optional[Any] = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() UpperCAmelCase : List[str] = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 UpperCAmelCase : Tuple = """Training loss: {:.2e} lr: {:.2e}""".format(UpperCamelCase , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer UpperCAmelCase : List[Any] = model.module if hasattr(UpperCamelCase , """module""" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` UpperCAmelCase : List[Any] = os.path.join(args.output_dir , UpperCamelCase ) UpperCAmelCase : List[str] = os.path.join(args.output_dir , UpperCamelCase ) torch.save(model_to_save.state_dict() , UpperCamelCase ) model_to_save.config.to_json_file(UpperCamelCase ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned UpperCAmelCase : Union[str, Any] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) UpperCAmelCase : Optional[Any] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(UpperCamelCase ) if args.do_eval: model.eval() UpperCAmelCase , UpperCAmelCase : int = 0, 0 UpperCAmelCase , UpperCAmelCase : int = 0, 0 for batch in tqdm(UpperCamelCase , desc="""Evaluating""" ): UpperCAmelCase : Tuple = tuple(t.to(UpperCamelCase ) for t in batch ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Optional[Any] = batch with torch.no_grad(): UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : List[str] = model( UpperCamelCase , mc_token_ids=UpperCamelCase , lm_labels=UpperCamelCase , mc_labels=UpperCamelCase ) UpperCAmelCase : List[str] = mc_logits.detach().cpu().numpy() UpperCAmelCase : Dict = mc_labels.to("""cpu""" ).numpy() UpperCAmelCase : str = accuracy(UpperCamelCase , UpperCamelCase ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 UpperCAmelCase : List[Any] = eval_loss / nb_eval_steps UpperCAmelCase : Dict = eval_accuracy / nb_eval_examples UpperCAmelCase : Union[str, Any] = tr_loss / nb_tr_steps if args.do_train else None UpperCAmelCase : str = {"""eval_loss""": eval_loss, """eval_accuracy""": eval_accuracy, """train_loss""": train_loss} UpperCAmelCase : Optional[int] = os.path.join(args.output_dir , """eval_results.txt""" ) with open(UpperCamelCase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , UpperCamelCase , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) if __name__ == "__main__": main()
109
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): 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 token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase = { 'configuration_nezha': ['NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'NezhaConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ 'NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST', 'NezhaForNextSentencePrediction', 'NezhaForMaskedLM', 'NezhaForPreTraining', 'NezhaForMultipleChoice', 'NezhaForQuestionAnswering', 'NezhaForSequenceClassification', 'NezhaForTokenClassification', 'NezhaModel', 'NezhaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
110
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
'''simple docstring''' import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def A__ ( UpperCAmelCase_ ): _UpperCamelCase : List[Any] = os.path.join(args.tf_model_dir , 'parameters.json' ) _UpperCamelCase : Union[str, Any] = json.loads(open(__A ).read() ) if not params: raise ValueError( f'It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.' ) if not args.output.endswith('.pt' ): _UpperCamelCase : List[Any] = args.output + '.pt' _UpperCamelCase : List[Any] = OrderedDict() with tf.device('/CPU:0' ): _UpperCamelCase : Dict = tf.train.load_checkpoint(args.tf_model_dir ) _UpperCamelCase : Dict = reader.get_variable_to_shape_map() for key_name in shapes.keys(): _UpperCamelCase : List[str] = reader.get_tensor(__A ).astype(np.floataa ) if key_name.endswith('/adam_m' ) or key_name.endswith('/adam_v' ): continue if key_name.startswith('pasts/' ): if key_name.startswith('pasts/mlp' ): _UpperCamelCase : Tuple = int(key_name[9] ) elif key_name.startswith('pasts/out' ): _UpperCamelCase : str = 8 _UpperCamelCase : str = 'model.sqout.%d.weight' % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time _UpperCamelCase : Tuple = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : int = torch.tensor(__A ) elif key_name.startswith('model/moe' ): _UpperCamelCase : List[Any] = int(key_name[9:].split('/' )[0] ) if key_name.endswith('/switch_gating/kernel' ): _UpperCamelCase : Dict = 'model.blocks.%d.feed_forward.mlp.router.classifier.weight' % player _UpperCamelCase : str = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : Tuple = torch.tensor(__A ) elif key_name.endswith('/softmlp/kernel' ): _UpperCamelCase : int = 'model.blocks.%d.feed_forward.soft_bypass_mlp.weight' % player _UpperCamelCase : int = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : List[Any] = torch.tensor(__A ) elif key_name.endswith('/wo/kernel' ) or key_name.endswith('/wi/kernel' ): _UpperCamelCase : List[Any] = key_name[-9:-7] for i in range(1_6 ): _UpperCamelCase : Tuple = 'model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight' % (player, i, nlayer) _UpperCamelCase : Tuple = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided _UpperCamelCase : str = torch.tensor(__A ) elif key_name.startswith('model/mlp' ): _UpperCamelCase : Union[str, Any] = int(key_name[9:].split('/' )[0] ) if key_name.endswith('/p1/kernel' ): _UpperCamelCase : str = 'model.blocks.%d.feed_forward.mlp.wi.weight' % player _UpperCamelCase : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : List[str] = torch.tensor(__A ) elif key_name.endswith('/p1/bias' ): _UpperCamelCase : List[str] = 'model.blocks.%d.feed_forward.mlp.wi.bias' % player _UpperCamelCase : Optional[int] = vnp.copy() # same because it is one dimensional _UpperCamelCase : Tuple = torch.tensor(__A ) elif key_name.endswith('/p2/kernel' ): _UpperCamelCase : Union[str, Any] = 'model.blocks.%d.feed_forward.mlp.wo.weight' % player _UpperCamelCase : Tuple = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : int = torch.tensor(__A ) elif key_name.endswith('/p2/bias' ): _UpperCamelCase : str = 'model.blocks.%d.feed_forward.mlp.wo.bias' % player _UpperCamelCase : Optional[int] = vnp.copy() # same because it is one dimensional _UpperCamelCase : int = torch.tensor(__A ) elif key_name.startswith('model/ln' ): _UpperCamelCase : Dict = int(key_name[8:].split('/' )[0] ) if key_name.endswith('/b' ): _UpperCamelCase : Optional[Any] = 'model.blocks.%d.feed_forward.norm.bias' % player _UpperCamelCase : str = vnp.copy() # same because it is one dimensional _UpperCamelCase : Optional[Any] = torch.tensor(__A ) elif key_name.endswith('/g' ): _UpperCamelCase : List[Any] = 'model.blocks.%d.feed_forward.norm.weight' % player _UpperCamelCase : Dict = vnp.copy() # same because it is one dimensional _UpperCamelCase : int = torch.tensor(__A ) elif key_name.startswith('model/att' ): _UpperCamelCase : Union[str, Any] = int(key_name[9:].split('/' )[0] ) if key_name.endswith('/qkv/kernel' ): _UpperCamelCase : Any = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum _UpperCamelCase : Any = state[:, 0, :, :] _UpperCamelCase : List[str] = state[:, 1, :, :] _UpperCamelCase : Union[str, Any] = state[:, 2, :, :] _UpperCamelCase : List[Any] = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : str = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : Any = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : Dict = 'model.blocks.%d.self_attn.self_attn.q_proj.weight' % player _UpperCamelCase : Any = torch.tensor(__A ) _UpperCamelCase : Optional[int] = 'model.blocks.%d.self_attn.self_attn.k_proj.weight' % player _UpperCamelCase : Optional[int] = torch.tensor(__A ) _UpperCamelCase : int = 'model.blocks.%d.self_attn.self_attn.v_proj.weight' % player _UpperCamelCase : int = torch.tensor(__A ) elif key_name.endswith('/o/kernel' ): _UpperCamelCase : Union[str, Any] = 'model.blocks.%d.self_attn.self_attn.out_proj.weight' % player _UpperCamelCase : List[Any] = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : Optional[int] = torch.tensor(__A ) elif key_name.startswith('model/an' ): _UpperCamelCase : str = int(key_name[8:].split('/' )[0] ) if key_name.endswith('/b' ): _UpperCamelCase : List[str] = 'model.blocks.%d.self_attn.norm.bias' % player _UpperCamelCase : Any = vnp.copy() # same because it is one dimensional _UpperCamelCase : List[Any] = torch.tensor(__A ) elif key_name.endswith('/g' ): _UpperCamelCase : Optional[Any] = 'model.blocks.%d.self_attn.norm.weight' % player _UpperCamelCase : Optional[int] = vnp.copy() # same because it is one dimensional _UpperCamelCase : List[Any] = torch.tensor(__A ) elif ( key_name.startswith('model/wte' ) or key_name.startswith('model/wpe' ) or key_name.startswith('model/ete' ) ): _UpperCamelCase : Any = {'wte': 'embed_tokens', 'wpe': 'position_embeddings', 'ete': 'extra_position_embeddings'}[ key_name[-3:] ] _UpperCamelCase : List[str] = 'model.%s.weight' % nlayer _UpperCamelCase : List[Any] = vnp.copy() # same in embedded _UpperCamelCase : int = torch.tensor(__A ) if key_name.startswith('model/wte' ): _UpperCamelCase : Any = 'lm_head.weight' _UpperCamelCase : List[str] = vnp.copy() # same in embedded _UpperCamelCase : Optional[int] = torch.tensor(__A ) elif key_name.startswith('model/wob' ): _UpperCamelCase : int = 'final_logits_bias' _UpperCamelCase : Tuple = vnp.copy() # same in embedded _UpperCamelCase : Tuple = state.reshape((1, -1) ) _UpperCamelCase : List[Any] = torch.tensor(__A ) elif key_name == "model/dense/kernel": _UpperCamelCase : Optional[Any] = 'model.last_project.weight' _UpperCamelCase : Optional[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _UpperCamelCase : Any = torch.tensor(__A ) elif key_name == "model/dense_1/bias": _UpperCamelCase : int = 'model.last_project.bias' _UpperCamelCase : Optional[int] = vnp.copy() # same because it is one dimensional _UpperCamelCase : List[Any] = torch.tensor(__A ) torch.save(__A , args.output ) if __name__ == "__main__": snake_case_ : Dict = argparse.ArgumentParser( description='model converter.', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--tf_model_dir', metavar='PATH', type=str, required=True, help='import model') parser.add_argument('--output', metavar='PATH', type=str, required=True, help='output model') snake_case_ : int = parser.parse_args() convert_tf_gptsan_to_pt(args)
83
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class a ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCAmelCase ( self ) -> Optional[Any]: _A , _A = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-canny""" , from_pt=lowerCAmelCase_ , dtype=jnp.bfloataa ) _A , _A = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=lowerCAmelCase_ , from_pt=lowerCAmelCase_ , dtype=jnp.bfloataa ) _A = controlnet_params _A = """bird""" _A = jax.device_count() _A = pipe.prepare_text_inputs([prompts] * num_samples ) _A = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ) _A = pipe.prepare_image_inputs([canny_image] * num_samples ) _A = jax.random.PRNGKey(0 ) _A = jax.random.split(lowerCAmelCase_ , jax.device_count() ) _A = replicate(lowerCAmelCase_ ) _A = shard(lowerCAmelCase_ ) _A = shard(lowerCAmelCase_ ) _A = pipe( prompt_ids=lowerCAmelCase_ , image=lowerCAmelCase_ , params=lowerCAmelCase_ , prng_seed=lowerCAmelCase_ , num_inference_steps=50 , jit=lowerCAmelCase_ , ).images assert images.shape == (jax.device_count(), 1, 7_68, 5_12, 3) _A = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) _A = images[0, 2_53:2_56, 2_53:2_56, -1] _A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) _A = jnp.array( [0.16_7969, 0.11_6699, 0.08_1543, 0.15_4297, 0.13_2812, 0.10_8887, 0.16_9922, 0.16_9922, 0.20_5078] ) print(F'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def UpperCAmelCase ( self ) -> List[Any]: _A , _A = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-openpose""" , from_pt=lowerCAmelCase_ , dtype=jnp.bfloataa ) _A , _A = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=lowerCAmelCase_ , from_pt=lowerCAmelCase_ , dtype=jnp.bfloataa ) _A = controlnet_params _A = """Chef in the kitchen""" _A = jax.device_count() _A = pipe.prepare_text_inputs([prompts] * num_samples ) _A = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png""" ) _A = pipe.prepare_image_inputs([pose_image] * num_samples ) _A = jax.random.PRNGKey(0 ) _A = jax.random.split(lowerCAmelCase_ , jax.device_count() ) _A = replicate(lowerCAmelCase_ ) _A = shard(lowerCAmelCase_ ) _A = shard(lowerCAmelCase_ ) _A = pipe( prompt_ids=lowerCAmelCase_ , image=lowerCAmelCase_ , params=lowerCAmelCase_ , prng_seed=lowerCAmelCase_ , num_inference_steps=50 , jit=lowerCAmelCase_ , ).images assert images.shape == (jax.device_count(), 1, 7_68, 5_12, 3) _A = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) _A = images[0, 2_53:2_56, 2_53:2_56, -1] _A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) _A = jnp.array( [[0.27_1484, 0.26_1719, 0.27_5391, 0.27_7344, 0.27_9297, 0.29_1016, 0.29_4922, 0.30_2734, 0.30_2734]] ) print(F'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
180
'''simple docstring''' # Copyright 2021 The HuggingFace 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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
'''simple docstring''' import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class __magic_name__ ( unittest.TestCase): def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): lowercase_ : Any = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : Any = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : Optional[Any] = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): lowercase_ : Any = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : Optional[int] = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): lowercase_ : Optional[Any] = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] lowercase_ : Optional[int] = """fp16""" self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): lowercase_ : List[Any] = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] lowercase_ : Any = """fp16""" self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): # pass variant but use the non-variant filenames lowercase_ : Optional[Any] = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] lowercase_ : Tuple = """fp16""" self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : Dict = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] lowercase_ : Any = """fp16""" self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : str ): lowercase_ : Optional[Any] = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] lowercase_ : List[str] = """fp16""" self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): # pass variant but use the non-variant filenames lowercase_ : Optional[Any] = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] lowercase_ : List[str] = """fp16""" self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ): lowercase_ : Optional[int] = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] lowercase_ : Tuple = """fp16""" self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_ ) )
239
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __SCREAMING_SNAKE_CASE : Tuple = {'UserAgent': UserAgent().random} def UpperCamelCase_ ( _UpperCAmelCase : int ) -> dict: """simple docstring""" _UpperCAmelCase : Tuple = script.contents[0] _UpperCAmelCase : Optional[int] = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowerCamelCase_ : '''simple docstring''' def __init__( self : List[Any] , A : List[Any] ): _UpperCAmelCase : str = F"""https://www.instagram.com/{username}/""" _UpperCAmelCase : str = self.get_json() def _A ( self : str ): _UpperCAmelCase : Tuple = requests.get(self.url , headers=A ).text _UpperCAmelCase : Optional[Any] = BeautifulSoup(A , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Union[str, Any] ): return F"""{self.__class__.__name__}(\'{self.username}\')""" def __str__( self : int ): return F"""{self.fullname} ({self.username}) is {self.biography}""" @property def _A ( self : Union[str, Any] ): return self.user_data["username"] @property def _A ( self : List[str] ): return self.user_data["full_name"] @property def _A ( self : Any ): return self.user_data["biography"] @property def _A ( self : str ): return self.user_data["business_email"] @property def _A ( self : Any ): return self.user_data["external_url"] @property def _A ( self : Tuple ): return self.user_data["edge_followed_by"]["count"] @property def _A ( self : Dict ): return self.user_data["edge_follow"]["count"] @property def _A ( self : Dict ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def _A ( self : Union[str, Any] ): return self.user_data["profile_pic_url_hd"] @property def _A ( self : Any ): return self.user_data["is_verified"] @property def _A ( self : Dict ): return self.user_data["is_private"] def UpperCamelCase_ ( _UpperCAmelCase : Any = "github" ) -> None: """simple docstring""" import os if os.environ.get("CI" ): return # test failing on GitHub Actions _UpperCAmelCase : Tuple = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120_000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE : Any = InstagramUser("""github""") print(instagram_user) print(F'{instagram_user.number_of_posts = }') print(F'{instagram_user.number_of_followers = }') print(F'{instagram_user.number_of_followings = }') print(F'{instagram_user.email = }') print(F'{instagram_user.website = }') print(F'{instagram_user.profile_picture_url = }') print(F'{instagram_user.is_verified = }') print(F'{instagram_user.is_private = }')
31
'''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 ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\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 , *a , **a ): 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. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = 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. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = 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']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} 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`" ) UpperCamelCase__ = 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`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = 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." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments 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 , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = 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: UpperCamelCase__ = 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" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = 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. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "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: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "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 UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = 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 __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = 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: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
import argparse import os from accelerate.test_utils import execute_subprocess_async def SCREAMING_SNAKE_CASE ( _UpperCAmelCase=None ) -> List[Any]: if subparsers is not None: lowerCamelCase__ : str = subparsers.add_parser('test' ) else: lowerCamelCase__ : List[str] = argparse.ArgumentParser('Accelerate test command' ) parser.add_argument( '--config_file' , default=__A , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=__A ) return parser def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Any: lowerCamelCase__ : List[Any] = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['test_utils', 'scripts', 'test_script.py'] ) if args.config_file is None: lowerCamelCase__ : str = script_name else: lowerCamelCase__ : List[Any] = F"""--config_file={args.config_file} {script_name}""" lowerCamelCase__ : Optional[Any] = ['accelerate-launch'] + test_args.split() lowerCamelCase__ : Union[str, Any] = execute_subprocess_async(__A , env=os.environ.copy() ) if result.returncode == 0: print('Test is a success! You are ready for your distributed training!' ) def SCREAMING_SNAKE_CASE ( ) -> int: lowerCamelCase__ : Any = test_command_parser() lowerCamelCase__ : Union[str, Any] = parser.parse_args() test_command(__A ) if __name__ == "__main__": main()
50
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
"""simple docstring""" import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: a__: Optional[Any] = FunnelConfig.from_json_file(__A ) print(F'Building PyTorch model from configuration: {config}' ) a__: Tuple = FunnelBaseModel(__A ) if base_model else FunnelModel(__A ) # Load weights from tf checkpoint load_tf_weights_in_funnel(__A , __A , __A ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , __A ) if __name__ == "__main__": lowercase__ = 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 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.' ) parser.add_argument( '--base_model', action='store_true', help='Whether you want just the base model (no decoder) or not.' ) lowercase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
290
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_time_series_transformer': [ 'TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimeSeriesTransformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Tuple = [ 'TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimeSeriesTransformerForPrediction', 'TimeSeriesTransformerModel', 'TimeSeriesTransformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
127
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
def A ( _lowercase , _lowercase , _lowercase=False ): if isinstance(__A , __A ) and isinstance(__A , __A ): SCREAMING_SNAKE_CASE : List[str] = len(set_a.intersection(__A ) ) if alternative_union: SCREAMING_SNAKE_CASE : str = len(__A ) + len(__A ) else: SCREAMING_SNAKE_CASE : Optional[int] = len(set_a.union(__A ) ) return intersection / union if isinstance(__A , (list, tuple) ) and isinstance(__A , (list, tuple) ): SCREAMING_SNAKE_CASE : List[Any] = [element for element in set_a if element in set_b] if alternative_union: SCREAMING_SNAKE_CASE : Any = len(__A ) + len(__A ) return len(__A ) / union else: SCREAMING_SNAKE_CASE : str = set_a + [element for element in set_b if element not in set_a] return len(__A ) / len(__A ) return len(__A ) / len(__A ) return None if __name__ == "__main__": __UpperCamelCase : Optional[Any] = {'a', 'b', 'c', 'd', 'e'} __UpperCamelCase : int = {'c', 'd', 'e', 'f', 'h', 'i'} print(jaccard_similarity(set_a, set_b))
182
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
from __future__ import annotations def lowercase( UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None ) -> None: '''simple docstring''' if start is None: UpperCamelCase = 0 if end is None: UpperCamelCase = len(__A ) - 1 if start >= end: return UpperCamelCase = (start + end) // 2 slowsort(__A , __A , __A ) slowsort(__A , mid + 1 , __A ) if sequence[end] < sequence[mid]: UpperCamelCase , UpperCamelCase = sequence[mid], sequence[end] slowsort(__A , __A , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
343
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
'''simple docstring''' import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch A_ = 'sshleifer/bart-tiny-random' A_ = 'patrickvonplaten/t5-tiny-random' @require_torch class _snake_case ( unittest.TestCase ): @cached_property def __UpperCamelCase ( self : List[Any] ): return AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : Any ): SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE:Any = create_student_by_copying_alternating_layers(SCREAMING_SNAKE_CASE__ ,tempfile.mkdtemp() ,e=1 ,d=1 ) self.assertEqual(student.config.num_hidden_layers ,1 ) def __UpperCamelCase ( self : Any ): SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE:Optional[int] = create_student_by_copying_alternating_layers(SCREAMING_SNAKE_CASE__ ,tempfile.mkdtemp() ,e=1 ,d=SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : List[str] ): SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE:Tuple = create_student_by_copying_alternating_layers(SCREAMING_SNAKE_CASE__ ,tempfile.mkdtemp() ,e=1 ,d=SCREAMING_SNAKE_CASE__ ) self.assertEqual(student.config.encoder_layers ,1 ) self.assertEqual(student.config.decoder_layers ,self.teacher_config.encoder_layers ) def __UpperCamelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE:str = create_student_by_copying_alternating_layers(SCREAMING_SNAKE_CASE__ ,tempfile.mkdtemp() ,e=1 ,d=1 ) self.assertEqual(student.config.encoder_layers ,1 ) self.assertEqual(student.config.decoder_layers ,1 ) def __UpperCamelCase ( self : Union[str, Any] ): with self.assertRaises(SCREAMING_SNAKE_CASE__ ): create_student_by_copying_alternating_layers(SCREAMING_SNAKE_CASE__ ,tempfile.mkdtemp() ,e=SCREAMING_SNAKE_CASE__ ,d=SCREAMING_SNAKE_CASE__ )
139
'''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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = 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: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class __A ( a__ ): """simple docstring""" @staticmethod @abstractmethod def __lowercase ( lowerCamelCase__ ): """simple docstring""" raise NotImplementedError() @abstractmethod def __lowercase ( self ): """simple docstring""" raise NotImplementedError()
71
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = 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 __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class lowercase__ : def __init__( self : str ,lowerCamelCase__ : str ,lowerCamelCase__ : Dict=13 ,lowerCamelCase__ : List[str]=7 ,lowerCamelCase__ : Dict=True ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Optional[int]=True ,lowerCamelCase__ : Tuple=True ,lowerCamelCase__ : Tuple=99 ,lowerCamelCase__ : Tuple=32 ,lowerCamelCase__ : str=2 ,lowerCamelCase__ : Any=4 ,lowerCamelCase__ : List[str]=37 ,lowerCamelCase__ : str="gelu" ,lowerCamelCase__ : Optional[int]=0.1 ,lowerCamelCase__ : List[Any]=0.1 ,lowerCamelCase__ : Dict=512 ,lowerCamelCase__ : int=16 ,lowerCamelCase__ : Any=2 ,lowerCamelCase__ : Any=0.0_2 ,lowerCamelCase__ : Any=3 ,lowerCamelCase__ : Optional[Any]=4 ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : List[str]=1000 ,): '''simple docstring''' _UpperCamelCase : List[str] = parent _UpperCamelCase : Dict = batch_size _UpperCamelCase : Tuple = seq_length _UpperCamelCase : Union[str, Any] = is_training _UpperCamelCase : Optional[Any] = use_input_mask _UpperCamelCase : Tuple = use_token_type_ids _UpperCamelCase : Optional[int] = use_labels _UpperCamelCase : Union[str, Any] = vocab_size _UpperCamelCase : Optional[Any] = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : List[str] = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : Optional[Any] = hidden_act _UpperCamelCase : List[str] = hidden_dropout_prob _UpperCamelCase : int = attention_probs_dropout_prob _UpperCamelCase : List[Any] = max_position_embeddings _UpperCamelCase : List[Any] = type_vocab_size _UpperCamelCase : int = type_sequence_label_size _UpperCamelCase : Union[str, Any] = initializer_range _UpperCamelCase : str = num_labels _UpperCamelCase : Optional[Any] = num_choices _UpperCamelCase : str = scope _UpperCamelCase : Any = range_bbox def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' _UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) # convert bbox to numpy since TF does not support item assignment _UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length, 4] ,self.range_bbox ).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: _UpperCamelCase : Union[str, Any] = bbox[i, j, 3] _UpperCamelCase : Optional[Any] = bbox[i, j, 1] _UpperCamelCase : Union[str, Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: _UpperCamelCase : Optional[int] = bbox[i, j, 2] _UpperCamelCase : Optional[Any] = bbox[i, j, 0] _UpperCamelCase : Optional[int] = t _UpperCamelCase : Optional[int] = tf.convert_to_tensor(lowerCamelCase__ ) _UpperCamelCase : str = None if self.use_input_mask: _UpperCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase : str = None if self.use_token_type_ids: _UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) _UpperCamelCase : Dict = None _UpperCamelCase : Tuple = None _UpperCamelCase : List[Any] = None if self.use_labels: _UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) _UpperCamelCase : List[str] = ids_tensor([self.batch_size] ,self.num_choices ) _UpperCamelCase : Optional[Any] = LayoutLMConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,) return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : int ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : int ,lowerCamelCase__ : int ): '''simple docstring''' _UpperCamelCase : Optional[int] = TFLayoutLMModel(config=lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = model(lowerCamelCase__ ,lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) _UpperCamelCase : str = model(lowerCamelCase__ ,lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) _UpperCamelCase : List[str] = model(lowerCamelCase__ ,lowerCamelCase__ ) 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 : List[str] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : Any ,lowerCamelCase__ : Any ,lowerCamelCase__ : str ): '''simple docstring''' _UpperCamelCase : List[str] = TFLayoutLMForMaskedLM(config=lowerCamelCase__ ) _UpperCamelCase : Optional[int] = model(lowerCamelCase__ ,lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Any ,lowerCamelCase__ : str ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : int ,lowerCamelCase__ : str ,lowerCamelCase__ : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : int = self.num_labels _UpperCamelCase : List[str] = TFLayoutLMForSequenceClassification(config=lowerCamelCase__ ) _UpperCamelCase : Dict = model(lowerCamelCase__ ,lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : str ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : int ): '''simple docstring''' _UpperCamelCase : int = self.num_labels _UpperCamelCase : Tuple = TFLayoutLMForTokenClassification(config=lowerCamelCase__ ) _UpperCamelCase : List[str] = model(lowerCamelCase__ ,lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : List[str] ): '''simple docstring''' _UpperCamelCase : List[Any] = TFLayoutLMForQuestionAnswering(config=lowerCamelCase__ ) _UpperCamelCase : Optional[int] = model(lowerCamelCase__ ,lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' _UpperCamelCase : int = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) : int = config_and_inputs _UpperCamelCase : List[Any] = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class lowercase__ ( a__ , a__ , unittest.TestCase ): lowercase__ = ( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) lowercase__ = ( { """feature-extraction""": TFLayoutLMModel, """fill-mask""": TFLayoutLMForMaskedLM, """text-classification""": TFLayoutLMForSequenceClassification, """token-classification""": TFLayoutLMForTokenClassification, """zero-shot""": TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) lowercase__ = False lowercase__ = True lowercase__ = 10 def UpperCamelCase_ ( self : int ): '''simple docstring''' _UpperCamelCase : List[Any] = TFLayoutLMModelTester(self ) _UpperCamelCase : str = ConfigTester(self ,config_class=lowerCamelCase__ ,hidden_size=37 ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def UpperCamelCase_ ( self : str ): '''simple docstring''' _UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__ ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase__ ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__ ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' _UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__ ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase : str = TFLayoutLMModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @unittest.skip('Onnx compliancy broke with TF 2.10' ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass def A__ ( ): _UpperCamelCase : str = tf.convert_to_tensor([[1_0_1,1_0_1_9,1_0_1_4,1_0_1_6,1_0_3_7,1_2_8_4_9,4_7_4_7,1_0_0_4,1_4_2_4_6,2_2_7_8,5_4_3_9,4_5_2_4,5_0_0_2,2_9_3_0,2_1_9_3,2_9_3_0,4_3_4_1,3_2_0_8,1_0_0_5,1_0_5_5,2_1_7_1,2_8_4_8,1_1_3_0_0,3_5_3_1,1_0_2],[1_0_1,4_0_7_0,4_0_3_4,7_0_2_0,1_0_2_4,3_0_5_8,1_0_1_5,1_0_1_3,2_8_6_1,1_0_1_3,6_0_7_0,1_9_2_7_4,2_7_7_2,6_2_0_5,2_7_8_1_4,1_6_1_4_7,1_6_1_4_7,4_3_4_3,2_0_4_7,1_0_2_8_3,1_0_9_6_9,1_4_3_8_9,1_0_1_2,2_3_3_8,1_0_2]] ) # noqa: E231 _UpperCamelCase : int = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 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: E231 _UpperCamelCase : Tuple = tf.convert_to_tensor([[[0,0,0,0],[4_2_3,2_3_7,4_4_0,2_5_1],[4_2_7,2_7_2,4_4_1,2_8_7],[4_1_9,1_1_5,4_3_7,1_2_9],[9_6_1,8_8_5,9_9_2,9_1_2],[2_5_6,3_8,3_3_0,5_8],[2_5_6,3_8,3_3_0,5_8],[3_3_6,4_2,3_5_3,5_7],[3_6_0,3_9,4_0_1,5_6],[3_6_0,3_9,4_0_1,5_6],[4_1_1,3_9,4_7_1,5_9],[4_7_9,4_1,5_2_8,5_9],[5_3_3,3_9,6_3_0,6_0],[6_7,1_1_3,1_3_4,1_3_1],[1_4_1,1_1_5,2_0_9,1_3_2],[6_8,1_4_9,1_3_3,1_6_6],[1_4_1,1_4_9,1_8_7,1_6_4],[1_9_5,1_4_8,2_8_7,1_6_5],[1_9_5,1_4_8,2_8_7,1_6_5],[1_9_5,1_4_8,2_8_7,1_6_5],[2_9_5,1_4_8,3_4_9,1_6_5],[4_4_1,1_4_9,4_9_2,1_6_6],[4_9_7,1_4_9,5_4_6,1_6_4],[6_4,2_0_1,1_2_5,2_1_8],[1_0_0_0,1_0_0_0,1_0_0_0,1_0_0_0]],[[0,0,0,0],[6_6_2,1_5_0,7_5_4,1_6_6],[6_6_5,1_9_9,7_4_2,2_1_1],[5_1_9,2_1_3,5_5_4,2_2_8],[5_1_9,2_1_3,5_5_4,2_2_8],[1_3_4,4_3_3,1_8_7,4_5_4],[1_3_0,4_6_7,2_0_4,4_8_0],[1_3_0,4_6_7,2_0_4,4_8_0],[1_3_0,4_6_7,2_0_4,4_8_0],[1_3_0,4_6_7,2_0_4,4_8_0],[1_3_0,4_6_7,2_0_4,4_8_0],[3_1_4,4_6_9,3_7_6,4_8_2],[5_0_4,6_8_4,5_8_2,7_0_6],[9_4_1,8_2_5,9_7_3,9_0_0],[9_4_1,8_2_5,9_7_3,9_0_0],[9_4_1,8_2_5,9_7_3,9_0_0],[9_4_1,8_2_5,9_7_3,9_0_0],[6_1_0,7_4_9,6_5_2,7_6_5],[1_3_0,6_5_9,1_6_8,6_7_2],[1_7_6,6_5_7,2_3_7,6_7_2],[2_3_8,6_5_7,3_1_2,6_7_2],[4_4_3,6_5_3,6_2_8,6_7_2],[4_4_3,6_5_3,6_2_8,6_7_2],[7_1_6,3_0_1,8_2_5,3_1_7],[1_0_0_0,1_0_0_0,1_0_0_0,1_0_0_0]]] ) # noqa: E231 _UpperCamelCase : Tuple = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,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: E231 # these are sequence labels (i.e. at the token level) _UpperCamelCase : str = tf.convert_to_tensor([[-1_0_0,1_0,1_0,1_0,9,1,-1_0_0,7,7,-1_0_0,7,7,4,2,5,2,8,8,-1_0_0,-1_0_0,5,0,3,2,-1_0_0],[-1_0_0,1_2,1_2,1_2,-1_0_0,1_2,1_0,-1_0_0,-1_0_0,-1_0_0,-1_0_0,1_0,1_2,9,-1_0_0,-1_0_0,-1_0_0,1_0,1_0,1_0,9,1_2,-1_0_0,1_0,-1_0_0]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' _UpperCamelCase : Any = TFLayoutLMModel.from_pretrained('microsoft/layoutlm-base-uncased' ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Any = prepare_layoutlm_batch_inputs() # forward pass _UpperCamelCase : List[Any] = model(input_ids=lowerCamelCase__ ,bbox=lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) # test the sequence output on [0, :3, :3] _UpperCamelCase : Any = tf.convert_to_tensor( [[0.1_7_8_5, -0.1_9_4_7, -0.0_4_2_5], [-0.3_2_5_4, -0.2_8_0_7, 0.2_5_5_3], [-0.5_3_9_1, -0.3_3_2_2, 0.3_3_6_4]] ,) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] ,lowerCamelCase__ ,atol=1E-3 ) ) # test the pooled output on [1, :3] _UpperCamelCase : str = tf.convert_to_tensor([-0.6_5_8_0, -0.0_2_1_4, 0.8_5_5_2] ) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] ,lowerCamelCase__ ,atol=1E-3 ) ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' # initialize model with randomly initialized sequence classification head _UpperCamelCase : str = TFLayoutLMForSequenceClassification.from_pretrained('microsoft/layoutlm-base-uncased' ,num_labels=2 ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Dict = prepare_layoutlm_batch_inputs() # forward pass _UpperCamelCase : Optional[int] = model( input_ids=lowerCamelCase__ ,bbox=lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=tf.convert_to_tensor([1, 1] ) ,) # test whether we get a loss as a scalar _UpperCamelCase : List[str] = outputs.loss _UpperCamelCase : Union[str, Any] = (2,) self.assertEqual(loss.shape ,lowerCamelCase__ ) # test the shape of the logits _UpperCamelCase : Optional[Any] = outputs.logits _UpperCamelCase : List[Any] = (2, 2) self.assertEqual(logits.shape ,lowerCamelCase__ ) @slow def UpperCamelCase_ ( self : Any ): '''simple docstring''' # initialize model with randomly initialized token classification head _UpperCamelCase : int = TFLayoutLMForTokenClassification.from_pretrained('microsoft/layoutlm-base-uncased' ,num_labels=13 ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : List[str] = prepare_layoutlm_batch_inputs() # forward pass _UpperCamelCase : int = model( input_ids=lowerCamelCase__ ,bbox=lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ) # test the shape of the logits _UpperCamelCase : List[str] = outputs.logits _UpperCamelCase : Union[str, Any] = tf.convert_to_tensor((2, 25, 13) ) self.assertEqual(logits.shape ,lowerCamelCase__ ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' # initialize model with randomly initialized token classification head _UpperCamelCase : Any = TFLayoutLMForQuestionAnswering.from_pretrained('microsoft/layoutlm-base-uncased' ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Tuple = prepare_layoutlm_batch_inputs() # forward pass _UpperCamelCase : Union[str, Any] = model(input_ids=lowerCamelCase__ ,bbox=lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) # test the shape of the logits _UpperCamelCase : Optional[int] = tf.convert_to_tensor((2, 25) ) self.assertEqual(outputs.start_logits.shape ,lowerCamelCase__ ) self.assertEqual(outputs.end_logits.shape ,lowerCamelCase__ )
83
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. _SCREAMING_SNAKE_CASE = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def snake_case ( snake_case__ :Optional[int]) -> Any: from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(__A) def snake_case ( snake_case__ :Union[str, Any]) -> Dict: from diffusers.utils.testing_utils import pytest_terminal_summary_main _A = terminalreporter.config.getoption("""--make-reports""") if make_reports: pytest_terminal_summary_main(__A , id=__A)
180
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Any = logging.get_logger(__name__) _lowercase : int = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __magic_name__ ( a__): UpperCamelCase__ = '''vit_msn''' def __init__( self : Union[str, Any] , lowercase_ : Optional[int]=768 , lowercase_ : Union[str, Any]=12 , lowercase_ : Any=12 , lowercase_ : int=3072 , lowercase_ : List[str]="gelu" , lowercase_ : Optional[int]=0.0 , lowercase_ : Optional[Any]=0.0 , lowercase_ : Tuple=0.02 , lowercase_ : int=1E-06 , lowercase_ : Union[str, Any]=224 , lowercase_ : str=16 , lowercase_ : Dict=3 , lowercase_ : Dict=True , **lowercase_ : Tuple , ): super().__init__(**lowercase_ ) lowercase_ : int = hidden_size lowercase_ : Optional[Any] = num_hidden_layers lowercase_ : List[Any] = num_attention_heads lowercase_ : Optional[Any] = intermediate_size lowercase_ : Optional[Any] = hidden_act lowercase_ : str = hidden_dropout_prob lowercase_ : Optional[Any] = attention_probs_dropout_prob lowercase_ : str = initializer_range lowercase_ : Dict = layer_norm_eps lowercase_ : Optional[Any] = image_size lowercase_ : Optional[int] = patch_size lowercase_ : Optional[Any] = num_channels lowercase_ : Dict = qkv_bias
239
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
'''simple docstring''' def UpperCamelCase_ ( _UpperCAmelCase : str , _UpperCAmelCase : Dict ) -> int: """simple docstring""" return x if y == 0 else greatest_common_divisor(__A , x % y ) def UpperCamelCase_ ( _UpperCAmelCase : Dict , _UpperCAmelCase : str ) -> int: """simple docstring""" return (x * y) // greatest_common_divisor(__A , __A ) def UpperCamelCase_ ( _UpperCAmelCase : Optional[Any] = 20 ) -> int: """simple docstring""" _UpperCAmelCase : int = 1 for i in range(1 , n + 1 ): _UpperCAmelCase : Optional[int] = lcm(__A , __A ) return g if __name__ == "__main__": print(F'{solution() = }')
31
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
import argparse import os import re _UpperCAmelCase : Optional[Any] = 'src/transformers/models/auto' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict _UpperCAmelCase : int = re.compile(R"""[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict""") # re pattern that matches identifiers in mappings _UpperCAmelCase : Optional[int] = re.compile(R"""\s*\(\s*\"(\S[^\"]+)\"""") def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase = False ) -> List[Any]: with open(__A , 'r' , encoding='utf-8' ) as f: lowerCamelCase__ : List[Any] = f.read() lowerCamelCase__ : Any = content.split('\n' ) lowerCamelCase__ : Optional[Any] = [] lowerCamelCase__ : int = 0 while line_idx < len(__A ): if _re_intro_mapping.search(lines[line_idx] ) is not None: lowerCamelCase__ : str = len(re.search(r'^(\s*)\S' , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(' ' * indent + '(' ): new_lines.append(lines[line_idx] ) line_idx += 1 lowerCamelCase__ : Any = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": lowerCamelCase__ : List[Any] = line_idx while not lines[line_idx].startswith(' ' * indent + ')' ): line_idx += 1 blocks.append('\n'.join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers lowerCamelCase__ : List[str] = sorted(__A , key=lambda _UpperCAmelCase : _re_identifier.search(__A ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(__A , 'w' , encoding='utf-8' ) as f: f.write('\n'.join(__A ) ) elif "\n".join(__A ) != content: return True def SCREAMING_SNAKE_CASE ( _UpperCAmelCase = False ) -> Optional[Any]: lowerCamelCase__ : int = [os.path.join(__A , __A ) for f in os.listdir(__A ) if f.endswith('.py' )] lowerCamelCase__ : str = [sort_auto_mapping(__A , overwrite=__A ) for fname in fnames] if not overwrite and any(__A ): lowerCamelCase__ : List[Any] = [f for f, d in zip(__A , __A ) if d] raise ValueError( F"""The following files have auto mappings that need sorting: {", ".join(__A )}. Run `make style` to fix""" ' this.' ) if __name__ == "__main__": _UpperCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""") _UpperCAmelCase : Tuple = parser.parse_args() sort_all_auto_mappings(not args.check_only)
50
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
"""simple docstring""" from math import factorial lowercase__ = {str(digit): factorial(digit) for digit in range(10)} def __a ( _SCREAMING_SNAKE_CASE ) ->int: if not isinstance(__A , __A ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(__A ) ) def __a ( _SCREAMING_SNAKE_CASE = 60 , _SCREAMING_SNAKE_CASE = 1000000 ) ->int: if not isinstance(__A , __A ) or not isinstance(__A , __A ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length a__: Optional[int] = 0 # the cached sizes of the previous chains a__: int = {} for start_chain_element in range(1 , __A ): # The temporary set will contain the elements of the chain a__: Union[str, Any] = set() a__: List[str] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a__: Tuple = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(__A ) chain_set_length += 1 a__: Any = digit_factorial_sum(__A ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a__: Dict = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution()}")
290
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer _SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Any = {'vocab_file': 'vocab.txt'} _SCREAMING_SNAKE_CASE : List[Any] = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } _SCREAMING_SNAKE_CASE : Optional[Any] = { 'YituTech/conv-bert-base': 5_12, 'YituTech/conv-bert-medium-small': 5_12, 'YituTech/conv-bert-small': 5_12, } _SCREAMING_SNAKE_CASE : int = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class A__ ( a__ ): """simple docstring""" __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_INIT_CONFIGURATION __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = ConvBertTokenizer def __init__( self , __snake_case=None , __snake_case=None , __snake_case=True , __snake_case="[UNK]" , __snake_case="[SEP]" , __snake_case="[PAD]" , __snake_case="[CLS]" , __snake_case="[MASK]" , __snake_case=True , __snake_case=None , **__snake_case , ): super().__init__( __snake_case , tokenizer_file=__snake_case , do_lower_case=__snake_case , unk_token=__snake_case , sep_token=__snake_case , pad_token=__snake_case , cls_token=__snake_case , mask_token=__snake_case , tokenize_chinese_chars=__snake_case , strip_accents=__snake_case , **__snake_case , ) snake_case = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __snake_case ) != do_lower_case or normalizer_state.get('''strip_accents''' , __snake_case ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __snake_case ) != tokenize_chinese_chars ): snake_case = getattr(__snake_case , normalizer_state.pop('''type''' ) ) snake_case = do_lower_case snake_case = strip_accents snake_case = tokenize_chinese_chars snake_case = normalizer_class(**__snake_case ) snake_case = do_lower_case def a_ ( self , __snake_case , __snake_case=None ): snake_case = [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 a_ ( self , __snake_case , __snake_case = None ): snake_case = [self.sep_token_id] snake_case = [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 a_ ( self , __snake_case , __snake_case = None ): snake_case = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case )
127
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
def A ( _lowercase ): if not numbers: return 0 if not isinstance(__A , (list, tuple) ) or not all( isinstance(__A , __A ) for number in numbers ): raise ValueError('''numbers must be an iterable of integers''' ) SCREAMING_SNAKE_CASE : List[Any] = numbers[0] for i in range(1 , len(__A ) ): # update the maximum and minimum subarray products SCREAMING_SNAKE_CASE : str = numbers[i] if number < 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = min_till_now, max_till_now SCREAMING_SNAKE_CASE : Tuple = max(__A , max_till_now * number ) SCREAMING_SNAKE_CASE : Optional[Any] = min(__A , min_till_now * number ) # update the maximum product found till now SCREAMING_SNAKE_CASE : List[str] = max(__A , __A ) return max_prod
182
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE_ ( a__ ): def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase_ , """embed_dim""" ) ) self.parent.assertTrue(hasattr(lowerCamelCase_ , """num_heads""" ) ) class SCREAMING_SNAKE_CASE_ : def __init__( self : List[str] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str]=13 , lowerCamelCase_ : Dict=64 , lowerCamelCase_ : Optional[int]=3 , lowerCamelCase_ : Any=[16, 48, 96] , lowerCamelCase_ : Union[str, Any]=[1, 3, 6] , lowerCamelCase_ : Dict=[1, 2, 10] , lowerCamelCase_ : str=[7, 3, 3] , lowerCamelCase_ : Any=[4, 2, 2] , lowerCamelCase_ : str=[2, 1, 1] , lowerCamelCase_ : Any=[2, 2, 2] , lowerCamelCase_ : Union[str, Any]=[False, False, True] , lowerCamelCase_ : List[Any]=[0.0, 0.0, 0.0] , lowerCamelCase_ : List[str]=0.0_2 , lowerCamelCase_ : Dict=1E-12 , lowerCamelCase_ : str=True , lowerCamelCase_ : Dict=True , lowerCamelCase_ : List[Any]=2 , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_sizes UpperCamelCase = patch_stride UpperCamelCase = patch_padding UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = num_labels UpperCamelCase = num_channels UpperCamelCase = embed_dim UpperCamelCase = num_heads UpperCamelCase = stride_kv UpperCamelCase = depth UpperCamelCase = cls_token UpperCamelCase = attention_drop_rate UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: # create a random int32 tensor of given shape UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int] ): """simple docstring""" UpperCamelCase = TFCvtModel(config=lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , training=lowerCamelCase_ ) UpperCamelCase = (self.image_size, self.image_size) UpperCamelCase , UpperCamelCase = image_size[0], image_size[1] for i in range(len(self.depth ) ): UpperCamelCase = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) UpperCamelCase = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int] ): """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = TFCvtForImageClassification(lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , labels=lowerCamelCase_ , training=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE_ ( a__ , a__ , unittest.TestCase ): __lowerCAmelCase = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () __lowerCAmelCase = ( {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification} if is_tf_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = TFCvtModelTester(self ) UpperCamelCase = TFCvtConfigTester(self , config_class=lowerCamelCase_ , has_text_modality=lowerCamelCase_ , hidden_size=37 ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" self.config_tester.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() @unittest.skip(reason="""Cvt does not output attentions""" ) def lowerCamelCase_ ( self : int ): """simple docstring""" pass @unittest.skip(reason="""Cvt does not use inputs_embeds""" ) def lowerCamelCase_ ( self : int ): """simple docstring""" pass @unittest.skip(reason="""Cvt does not support input and output embeddings""" ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def lowerCamelCase_ ( self : Dict ): """simple docstring""" super().test_keras_fit() @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""" ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = tf.keras.mixed_precision.Policy("""mixed_float16""" ) tf.keras.mixed_precision.set_global_policy(lowerCamelCase_ ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("""float32""" ) def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" def check_hidden_states_output(lowerCamelCase_ : List[str] , lowerCamelCase_ : str , lowerCamelCase_ : int ): UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = len(self.model_tester.depth ) self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_ ) @slow def lowerCamelCase_ ( self : List[str] ): """simple docstring""" for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = TFCvtModel.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) def lowercase( ) -> Optional[int]: '''simple docstring''' UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self : Tuple ): """simple docstring""" return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=lowerCamelCase_ , return_tensors="""tf""" ) # forward pass UpperCamelCase = model(**lowerCamelCase_ ) # verify the logits UpperCamelCase = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) UpperCamelCase = tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowerCamelCase_ , atol=1E-4 ) )
343
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): 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 , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("Googling.....") A_ = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) A_ = requests.get(url, headers={"UserAgent": UserAgent().random}) # res.raise_for_status() with open("project1a.html", "wb") as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) A_ = BeautifulSoup(res.text, "html.parser") A_ = list(soup.select(".eZt8xd"))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("href")) else: webbrowser.open(f'''https://google.com{link.get("href")}''')
139
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): 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 token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : int =TFXLMRobertaModel.from_pretrained('jplu/tf-xlm-roberta-base' ) __UpperCamelCase : Dict ={ 'input_ids': tf.convert_to_tensor([[0, 2646, 10269, 83, 99942, 2]] , dtype=tf.intaa ), # "My dog is cute" 'attention_mask': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } __UpperCamelCase : Optional[Any] =model(lowerCamelCase__ )['last_hidden_state'] __UpperCamelCase : Tuple =tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , lowerCamelCase__ ) # compare the actual values for a slice. __UpperCamelCase : Dict =tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
71
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig snake_case_ : Dict = { 'google/tapas-base-finetuned-sqa': ( 'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json' ), 'google/tapas-base-finetuned-wtq': ( 'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json' ), 'google/tapas-base-finetuned-wikisql-supervised': ( 'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json' ), 'google/tapas-base-finetuned-tabfact': ( 'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json' ), } class lowercase__ ( a__ ): lowercase__ = """tapas""" def __init__( self : List[Any] ,lowerCamelCase__ : List[Any]=30522 ,lowerCamelCase__ : Union[str, Any]=768 ,lowerCamelCase__ : Union[str, Any]=12 ,lowerCamelCase__ : List[Any]=12 ,lowerCamelCase__ : List[str]=3072 ,lowerCamelCase__ : List[str]="gelu" ,lowerCamelCase__ : int=0.1 ,lowerCamelCase__ : Optional[int]=0.1 ,lowerCamelCase__ : Tuple=1024 ,lowerCamelCase__ : List[str]=[3, 256, 256, 2, 256, 256, 10] ,lowerCamelCase__ : Any=0.0_2 ,lowerCamelCase__ : Any=1E-12 ,lowerCamelCase__ : Tuple=0 ,lowerCamelCase__ : Optional[Any]=1_0.0 ,lowerCamelCase__ : Union[str, Any]=0 ,lowerCamelCase__ : str=1.0 ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : Tuple=1.0 ,lowerCamelCase__ : int=False ,lowerCamelCase__ : Dict=None ,lowerCamelCase__ : Optional[Any]=1.0 ,lowerCamelCase__ : Any=1.0 ,lowerCamelCase__ : Dict=False ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : List[str]="ratio" ,lowerCamelCase__ : str=None ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : List[str]=64 ,lowerCamelCase__ : List[str]=32 ,lowerCamelCase__ : int=False ,lowerCamelCase__ : Tuple=True ,lowerCamelCase__ : List[Any]=False ,lowerCamelCase__ : Any=False ,lowerCamelCase__ : str=True ,lowerCamelCase__ : Any=False ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : List[Any]=None ,**lowerCamelCase__ : int ,): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) _UpperCamelCase : List[Any] = vocab_size _UpperCamelCase : Union[str, Any] = hidden_size _UpperCamelCase : Union[str, Any] = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Tuple = hidden_act _UpperCamelCase : int = intermediate_size _UpperCamelCase : str = hidden_dropout_prob _UpperCamelCase : Dict = attention_probs_dropout_prob _UpperCamelCase : Tuple = max_position_embeddings _UpperCamelCase : Optional[Any] = type_vocab_sizes _UpperCamelCase : List[str] = initializer_range _UpperCamelCase : Dict = layer_norm_eps # Fine-tuning task hyperparameters _UpperCamelCase : int = positive_label_weight _UpperCamelCase : str = num_aggregation_labels _UpperCamelCase : str = aggregation_loss_weight _UpperCamelCase : Any = use_answer_as_supervision _UpperCamelCase : str = answer_loss_importance _UpperCamelCase : Optional[int] = use_normalized_answer_loss _UpperCamelCase : Tuple = huber_loss_delta _UpperCamelCase : Union[str, Any] = temperature _UpperCamelCase : str = aggregation_temperature _UpperCamelCase : List[Any] = use_gumbel_for_cells _UpperCamelCase : int = use_gumbel_for_aggregation _UpperCamelCase : int = average_approximation_function _UpperCamelCase : List[str] = cell_selection_preference _UpperCamelCase : Any = answer_loss_cutoff _UpperCamelCase : int = max_num_rows _UpperCamelCase : int = max_num_columns _UpperCamelCase : Optional[Any] = average_logits_per_cell _UpperCamelCase : Union[str, Any] = select_one_column _UpperCamelCase : List[str] = allow_empty_column_selection _UpperCamelCase : List[str] = init_cell_selection_weights_to_zero _UpperCamelCase : Tuple = reset_position_index_per_cell _UpperCamelCase : str = disable_per_token_loss # Aggregation hyperparameters _UpperCamelCase : Tuple = aggregation_labels _UpperCamelCase : List[str] = no_aggregation_label_index if isinstance(self.aggregation_labels ,lowerCamelCase__ ): _UpperCamelCase : List[Any] = {int(lowerCamelCase__ ): v for k, v in aggregation_labels.items()}
83
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
_SCREAMING_SNAKE_CASE = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100_000)] def snake_case ( snake_case__ :Optional[int]) -> int: _A = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _SCREAMING_SNAKE_CASE = [None] * 10_000_000 _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False def snake_case ( snake_case__ :List[str]) -> bool: if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore _A = chain(next_number(__A)) _A = number_chain while number < 10_000_000: _A = number_chain number *= 10 return number_chain def snake_case ( snake_case__ :Any = 10_000_000) -> int: for i in range(1 , __A): if CHAINS[i] is None: chain(i + 1) return CHAINS[:number].count(__A) if __name__ == "__main__": import doctest doctest.testmod() print(F'''{solution() = }''')
180
'''simple docstring''' # Copyright 2021 The HuggingFace 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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase : Any = logging.get_logger(__name__) _lowercase : Union[str, Any] = '▁' _lowercase : Tuple = {'vocab_file': 'spiece.model'} _lowercase : Optional[Any] = { 'vocab_file': { 'google/reformer-crime-and-punishment': ( 'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model' ) } } _lowercase : List[Any] = { 'google/reformer-crime-and-punishment': 524288, } class __magic_name__ ( a__): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self : int , lowercase_ : int , lowercase_ : List[Any]="</s>" , lowercase_ : Dict="<unk>" , lowercase_ : str=[] , lowercase_ : List[Any] = None , **lowercase_ : Optional[Any] , ): lowercase_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowercase_ , unk_token=lowercase_ , additional_special_tokens=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) lowercase_ : int = vocab_file lowercase_ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase_ ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): return self.sp_model.get_piece_size() def SCREAMING_SNAKE_CASE_ ( self : Dict ): lowercase_ : List[Any] = {self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Tuple ): lowercase_ : List[str] = self.__dict__.copy() lowercase_ : Optional[Any] = None return state def __setstate__( self : str , lowercase_ : Tuple ): lowercase_ : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowercase_ : List[Any] = {} lowercase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , lowercase_ : str ): return self.sp_model.encode(lowercase_ , out_type=lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , lowercase_ : Dict ): return self.sp_model.piece_to_id(lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , lowercase_ : Any ): if index < self.sp_model.get_piece_size(): lowercase_ : List[Any] = self.sp_model.IdToPiece(lowercase_ ) return token def SCREAMING_SNAKE_CASE_ ( self : int , lowercase_ : str ): lowercase_ : int = [] lowercase_ : List[str] = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowercase_ ) + token lowercase_ : Tuple = [] else: current_sub_tokens.append(lowercase_ ) out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self : Tuple , lowercase_ : Union[str, Any] , lowercase_ : List[str] = None ): if not os.path.isdir(lowercase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Any = os.path.join( lowercase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase_ , """wb""" ) as fi: lowercase_ : List[Any] = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
239
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
'''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_barthez import BarthezTokenizer else: __SCREAMING_SNAKE_CASE : List[Any] = None __SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Any = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE : str = { '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' ), }, 'tokenizer_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json' ), }, } __SCREAMING_SNAKE_CASE : Any = { 'moussaKam/mbarthez': 1_024, 'moussaKam/barthez': 1_024, 'moussaKam/barthez-orangesum-title': 1_024, } __SCREAMING_SNAKE_CASE : int = '▁' class lowerCamelCase_ (a__ ): '''simple docstring''' __UpperCamelCase: Optional[int] = VOCAB_FILES_NAMES __UpperCamelCase: int = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase: List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase: int = ["input_ids", "attention_mask"] __UpperCamelCase: Dict = BarthezTokenizer def __init__( self : str , A : Any=None , A : Dict=None , A : Optional[Any]="<s>" , A : List[Any]="</s>" , A : Optional[Any]="</s>" , A : int="<s>" , A : int="<unk>" , A : List[Any]="<pad>" , A : Optional[Any]="<mask>" , **A : str , ): # Mask token behave like a normal word, i.e. include the space before it _UpperCAmelCase : Union[str, Any] = 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 , cls_token=A , pad_token=A , mask_token=A , **A , ) _UpperCAmelCase : str = vocab_file _UpperCAmelCase : Any = False if not self.vocab_file else True def _A ( self : List[str] , A : Union[str, Any] , A : Optional[Any] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _UpperCAmelCase : Dict = [self.cls_token_id] _UpperCAmelCase : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _A ( self : List[str] , A : Optional[int] , A : Optional[Any] = None ): _UpperCAmelCase : List[Any] = [self.sep_token_id] _UpperCAmelCase : 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 + sep + token_ids_a + sep ) * [0] def _A ( self : Union[str, Any] , A : Tuple , A : Dict = None ): 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 _UpperCAmelCase : Optional[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,)
31
'''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 ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\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 , *a , **a ): 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. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = 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. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = 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']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} 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`" ) UpperCamelCase__ = 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`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = 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." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments 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 , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = 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: UpperCamelCase__ = 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" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = 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. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "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: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "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 UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = 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 __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = 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: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
from __future__ import annotations from typing import Any def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> None: create_state_space_tree(__A , [] , 0 ) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> None: if index == len(__A ): print(__A ) return create_state_space_tree(__A , __A , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(__A , __A , index + 1 ) current_subsequence.pop() if __name__ == "__main__": _UpperCAmelCase : list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["""A""", """B""", """C"""]) generate_all_subsequences(seq)
50
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
"""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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging lowercase__ = logging.get_logger(__name__) if is_vision_available(): import PIL class __snake_case ( a__ ): a__ = ["""pixel_values"""] def __init__( self , lowercase = True , lowercase = None , lowercase = PILImageResampling.BICUBIC , lowercase = True , lowercase = None , lowercase = True , lowercase = 1 / 2_55 , lowercase = True , lowercase = None , lowercase = None , lowercase = True , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(**lowercase) a__: Tuple = size if size is not None else {'shortest_edge': 2_24} a__: str = get_size_dict(lowercase , default_to_square=lowercase) a__: str = crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24} a__: Any = get_size_dict(lowercase , default_to_square=lowercase , param_name='crop_size') a__: Optional[Any] = do_resize a__: Optional[Any] = size a__: Dict = resample a__: List[str] = do_center_crop a__: Dict = crop_size a__: int = do_rescale a__: Tuple = rescale_factor a__: Dict = do_normalize a__: Optional[int] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN a__: str = image_std if image_std is not None else OPENAI_CLIP_STD a__: str = do_convert_rgb def lowerCamelCase_ ( self , lowercase , lowercase , lowercase = PILImageResampling.BICUBIC , lowercase = None , **lowercase , ) -> Optional[Any]: '''simple docstring''' a__: str = get_size_dict(lowercase , default_to_square=lowercase) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}') a__: Optional[Any] = get_resize_output_image_size(lowercase , size=size['shortest_edge'] , default_to_square=lowercase) return resize(lowercase , size=lowercase , resample=lowercase , data_format=lowercase , **lowercase) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> Optional[Any]: '''simple docstring''' a__: List[Any] = get_size_dict(lowercase) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}') return center_crop(lowercase , size=(size['height'], size['width']) , data_format=lowercase , **lowercase) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> Dict: '''simple docstring''' return rescale(lowercase , scale=lowercase , data_format=lowercase , **lowercase) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase , lowercase = None , **lowercase , ) -> Any: '''simple docstring''' return normalize(lowercase , mean=lowercase , std=lowercase , data_format=lowercase , **lowercase) def lowerCamelCase_ ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> Dict: '''simple docstring''' a__: Union[str, Any] = do_resize if do_resize is not None else self.do_resize a__: Optional[int] = size if size is not None else self.size a__: Tuple = get_size_dict(lowercase , param_name='size' , default_to_square=lowercase) a__: Union[str, Any] = resample if resample is not None else self.resample a__: int = do_center_crop if do_center_crop is not None else self.do_center_crop a__: Union[str, Any] = crop_size if crop_size is not None else self.crop_size a__: Tuple = get_size_dict(lowercase , param_name='crop_size' , default_to_square=lowercase) a__: int = do_rescale if do_rescale is not None else self.do_rescale a__: int = rescale_factor if rescale_factor is not None else self.rescale_factor a__: List[Any] = do_normalize if do_normalize is not None else self.do_normalize a__: List[str] = image_mean if image_mean is not None else self.image_mean a__: int = image_std if image_std is not None else self.image_std a__: Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb a__: Optional[Any] = make_list_of_images(lowercase) if not valid_images(lowercase): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.') if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # PIL RGBA images are converted to RGB if do_convert_rgb: a__: Optional[Any] = [convert_to_rgb(lowercase) for image in images] # All transformations expect numpy arrays. a__: Optional[int] = [to_numpy_array(lowercase) for image in images] if do_resize: a__: Optional[int] = [self.resize(image=lowercase , size=lowercase , resample=lowercase) for image in images] if do_center_crop: a__: Dict = [self.center_crop(image=lowercase , size=lowercase) for image in images] if do_rescale: a__: int = [self.rescale(image=lowercase , scale=lowercase) for image in images] if do_normalize: a__: List[Any] = [self.normalize(image=lowercase , mean=lowercase , std=lowercase) for image in images] a__: List[Any] = [to_channel_dimension_format(lowercase , lowercase) for image in images] a__: Union[str, Any] = {'pixel_values': images} return BatchFeature(data=lowercase , tensor_type=lowercase)
290
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Dict = { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class A__ ( a__ ): """simple docstring""" __magic_name__ = 'speech_to_text_2' __magic_name__ = ['past_key_values'] __magic_name__ = {'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , __snake_case=1_0_0_0_0 , __snake_case=6 , __snake_case=2_0_4_8 , __snake_case=4 , __snake_case=0.0 , __snake_case=True , __snake_case="relu" , __snake_case=2_5_6 , __snake_case=0.1 , __snake_case=0.0 , __snake_case=0.0 , __snake_case=0.02 , __snake_case=2 , __snake_case=True , __snake_case=1 , __snake_case=0 , __snake_case=2 , __snake_case=1_0_2_4 , **__snake_case , ): snake_case = vocab_size snake_case = d_model snake_case = decoder_ffn_dim snake_case = decoder_layers snake_case = decoder_attention_heads snake_case = dropout snake_case = attention_dropout snake_case = activation_dropout snake_case = activation_function snake_case = init_std snake_case = decoder_layerdrop snake_case = use_cache snake_case = decoder_layers snake_case = scale_embedding # scale factor will be sqrt(d_model) if True snake_case = max_target_positions super().__init__( pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , decoder_start_token_id=__snake_case , **__snake_case , )
127
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) class lowercase__ ( a__): UpperCamelCase_ = ["""pixel_values"""] def __init__( self : Dict , UpperCamelCase__ : str = True , UpperCamelCase__ : Dict = None , UpperCamelCase__ : Optional[int] = PILImageResampling.BILINEAR , UpperCamelCase__ : str = True , UpperCamelCase__ : Tuple = 1 / 255 , UpperCamelCase__ : List[Any] = True , UpperCamelCase__ : Union[str, Any] = None , UpperCamelCase__ : List[Any] = True , **UpperCamelCase__ : Any , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = size if size is not None else {'''shortest_edge''': 224} SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = crop_size if crop_size is not None else {'''height''': 256, '''width''': 256} SCREAMING_SNAKE_CASE : str = get_size_dict(UpperCamelCase__ , param_name='''crop_size''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = do_resize SCREAMING_SNAKE_CASE : Dict = size SCREAMING_SNAKE_CASE : Optional[Any] = resample SCREAMING_SNAKE_CASE : Union[str, Any] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : List[str] = do_center_crop SCREAMING_SNAKE_CASE : Union[str, Any] = crop_size SCREAMING_SNAKE_CASE : Any = do_flip_channel_order def __A ( self : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[Any] = PIL.Image.BILINEAR , UpperCamelCase__ : Dict = None , **UpperCamelCase__ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size(UpperCamelCase__ , size=size['''shortest_edge'''] , default_to_square=UpperCamelCase__ ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any = None , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(UpperCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) return center_crop(UpperCamelCase__ , size=(size['''height'''], size['''width''']) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : str , UpperCamelCase__ : Dict = None , **UpperCamelCase__ : Tuple , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Any = None ): '''simple docstring''' return flip_channel_order(UpperCamelCase__ , data_format=UpperCamelCase__ ) def __A ( self : str , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict = None , UpperCamelCase__ : List[str] = None , UpperCamelCase__ : Union[str, Any] = None , UpperCamelCase__ : Tuple = None , UpperCamelCase__ : Tuple = None , UpperCamelCase__ : Union[str, Any] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : List[str] = None , UpperCamelCase__ : List[str] = None , UpperCamelCase__ : Any = ChannelDimension.FIRST , **UpperCamelCase__ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Any = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Any = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : List[str] = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Any = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCamelCase__ , param_name='''crop_size''' ) SCREAMING_SNAKE_CASE : Optional[Any] = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Tuple = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : int = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE : Optional[int] = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Union[str, Any] = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: SCREAMING_SNAKE_CASE : Tuple = [self.flip_channel_order(image=UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Dict = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ ) def __A ( self : str , UpperCamelCase__ : int , UpperCamelCase__ : List[str] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : int = target_sizes.numpy() SCREAMING_SNAKE_CASE : Tuple = [] for idx in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : int = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : Optional[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
182
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = { """task_specific_params""": { """summarization""": {"""length_penalty""": 1.0, """max_length""": 128, """min_length""": 12, """num_beams""": 4}, """summarization_cnn""": {"""length_penalty""": 2.0, """max_length""": 142, """min_length""": 56, """num_beams""": 4}, """summarization_xsum""": {"""length_penalty""": 1.0, """max_length""": 62, """min_length""": 11, """num_beams""": 6}, } } UpperCamelCase = { """task_specific_params.summarization.length_penalty""": 1.0, """task_specific_params.summarization.max_length""": 128, """task_specific_params.summarization.min_length""": 12, """task_specific_params.summarization.num_beams""": 4, """task_specific_params.summarization_cnn.length_penalty""": 2.0, """task_specific_params.summarization_cnn.max_length""": 142, """task_specific_params.summarization_cnn.min_length""": 56, """task_specific_params.summarization_cnn.num_beams""": 4, """task_specific_params.summarization_xsum.length_penalty""": 1.0, """task_specific_params.summarization_xsum.max_length""": 62, """task_specific_params.summarization_xsum.min_length""": 11, """task_specific_params.summarization_xsum.num_beams""": 6, } self.assertEqual(flatten_dict(lowerCamelCase_ ) , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ ) , x.transpose() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = torch.tensor(lowerCamelCase_ ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ ) , transpose(lowerCamelCase_ ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = torch.tensor(lowerCamelCase_ ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ , axes=(1, 2, 0) ) , transpose(lowerCamelCase_ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = tf.constant(lowerCamelCase_ ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ ) , transpose(lowerCamelCase_ ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = tf.constant(lowerCamelCase_ ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ , axes=(1, 2, 0) ) , transpose(lowerCamelCase_ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = jnp.array(lowerCamelCase_ ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ ) , np.asarray(transpose(lowerCamelCase_ ) ) ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = jnp.array(lowerCamelCase_ ) self.assertTrue(np.allclose(transpose(lowerCamelCase_ , axes=(1, 2, 0) ) , np.asarray(transpose(lowerCamelCase_ , axes=(1, 2, 0) ) ) ) ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (4, 3) ) , np.reshape(lowerCamelCase_ , (4, 3) ) ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (12, 5) ) , np.reshape(lowerCamelCase_ , (12, 5) ) ) ) @require_torch def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = torch.tensor(lowerCamelCase_ ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (4, 3) ) , reshape(lowerCamelCase_ , (4, 3) ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = torch.tensor(lowerCamelCase_ ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (12, 5) ) , reshape(lowerCamelCase_ , (12, 5) ).numpy() ) ) @require_tf def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = tf.constant(lowerCamelCase_ ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (4, 3) ) , reshape(lowerCamelCase_ , (4, 3) ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = tf.constant(lowerCamelCase_ ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (12, 5) ) , reshape(lowerCamelCase_ , (12, 5) ).numpy() ) ) @require_flax def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = jnp.array(lowerCamelCase_ ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (4, 3) ) , np.asarray(reshape(lowerCamelCase_ , (4, 3) ) ) ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = jnp.array(lowerCamelCase_ ) self.assertTrue(np.allclose(reshape(lowerCamelCase_ , (12, 5) ) , np.asarray(reshape(lowerCamelCase_ , (12, 5) ) ) ) ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ ) , np.squeeze(lowerCamelCase_ ) ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ , axis=2 ) , np.squeeze(lowerCamelCase_ , axis=2 ) ) ) @require_torch def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) UpperCamelCase = torch.tensor(lowerCamelCase_ ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ ) , squeeze(lowerCamelCase_ ).numpy() ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase = torch.tensor(lowerCamelCase_ ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ , axis=2 ) , squeeze(lowerCamelCase_ , axis=2 ).numpy() ) ) @require_tf def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) UpperCamelCase = tf.constant(lowerCamelCase_ ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ ) , squeeze(lowerCamelCase_ ).numpy() ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase = tf.constant(lowerCamelCase_ ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ , axis=2 ) , squeeze(lowerCamelCase_ , axis=2 ).numpy() ) ) @require_flax def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) UpperCamelCase = jnp.array(lowerCamelCase_ ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ ) , np.asarray(squeeze(lowerCamelCase_ ) ) ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase = jnp.array(lowerCamelCase_ ) self.assertTrue(np.allclose(squeeze(lowerCamelCase_ , axis=2 ) , np.asarray(squeeze(lowerCamelCase_ , axis=2 ) ) ) ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(lowerCamelCase_ , axis=1 ) , np.expand_dims(lowerCamelCase_ , axis=1 ) ) ) @require_torch def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = torch.tensor(lowerCamelCase_ ) self.assertTrue(np.allclose(expand_dims(lowerCamelCase_ , axis=1 ) , expand_dims(lowerCamelCase_ , axis=1 ).numpy() ) ) @require_tf def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = tf.constant(lowerCamelCase_ ) self.assertTrue(np.allclose(expand_dims(lowerCamelCase_ , axis=1 ) , expand_dims(lowerCamelCase_ , axis=1 ).numpy() ) ) @require_flax def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = jnp.array(lowerCamelCase_ ) self.assertTrue(np.allclose(expand_dims(lowerCamelCase_ , axis=1 ) , np.asarray(expand_dims(lowerCamelCase_ , axis=1 ) ) ) )
343
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate A_ = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow("", "|", "|"), datarow=DataRow("", "|", "|"), padding=1, with_header_hide=None, ) A_ = [] A_ = [] A_ = {'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} A_ = [ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': f'''🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results''', 'emoji': True, }, } ] A_ = 0 for log in Path().glob("*.log"): A_ = 0 with open(log, "r") as f: for line in f: A_ = json.loads(line) if line.get("nodeid", "") != "": A_ = line['nodeid'] if line.get("duration", None) is not None: A_ = f'''{line["duration"]:.4f}''' if line.get("outcome", "") == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split("_")[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) A_ = [] log.unlink() A_ = '' A_ = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += f"*{name[1:]}: {num_failed} failed test*\n" else: message += f"*{name[1:]}: {num_failed} failed tests*\n" A_ = [] A_ = {} for test in failed_tests: A_ = test[0].split("::") A_ = data[0].split("/")[-1] if data[0] not in filesafailed: A_ = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) A_ = [test[0] for test in failed_table] A_ = list(set(files)) # Count number of instances in failed_tests A_ = [] for file in individual_files: table.append([file, len(filesafailed[file])]) A_ = tabulate( table, headers=["Test Location", "Num Failed"], tablefmt=hf_table_format, stralign="right", ) message += f"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 30_00: A_ = 'Too many failed tests, please see the full report in the Action results.' A_ = len(err) + 10 A_ = message[: 30_00 - offset] + f'''\n...\n```\n{err}''' print(f'''### {message}''') else: A_ = 'No failed tests! 🤗' print(f'''## {message}''') payload.append(no_error_payload) if os.environ.get("TEST_TYPE", "") != "": from slack_sdk import WebClient A_ = WebClient(token=os.environ["SLACK_API_TOKEN"]) if message != "No failed tests! 🤗": A_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) A_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': f'''https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}''', }, } payload.append(action_button) A_ = { 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': f'''Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}''', } ], } payload.append(date_report) A_ = client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload) A_ = response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name A_ = '' for i, row in enumerate(test_failures): if row[0] != test_class: A_ = row[0] else: A_ = '' A_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': f'''Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```''', }, } client.chat_postMessage( channel="#accelerate-ci-daily", thread_ts=ts, blocks=[payload], )
139
'''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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = 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: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
A_ :Union[str, Any] = { 'meter': 'm', 'kilometer': 'km', 'megametre': 'Mm', 'gigametre': 'Gm', 'terametre': 'Tm', 'petametre': 'Pm', 'exametre': 'Em', 'zettametre': 'Zm', 'yottametre': 'Ym', } # Exponent of the factor(meter) A_ :Optional[int] = { 'm': 0, 'km': 3, 'Mm': 6, 'Gm': 9, 'Tm': 12, 'Pm': 15, 'Em': 18, 'Zm': 21, 'Ym': 24, } def A ( a_ ,a_ ,a_ ) -> float: __UpperCamelCase : Optional[Any] =from_type.lower().strip('s' ) __UpperCamelCase : Dict =to_type.lower().strip('s' ) __UpperCamelCase : Optional[Any] =UNIT_SYMBOL.get(__A ,__A ) __UpperCamelCase : List[Any] =UNIT_SYMBOL.get(__A ,__A ) if from_sanitized not in METRIC_CONVERSION: __UpperCamelCase : Optional[int] =( F'Invalid \'from_type\' value: {from_type!r}.\n' F'Conversion abbreviations are: {", ".join(__A )}' ) raise ValueError(__A ) if to_sanitized not in METRIC_CONVERSION: __UpperCamelCase : List[Any] =( F'Invalid \'to_type\' value: {to_type!r}.\n' F'Conversion abbreviations are: {", ".join(__A )}' ) raise ValueError(__A ) __UpperCamelCase : List[Any] =METRIC_CONVERSION[from_sanitized] __UpperCamelCase : Union[str, Any] =METRIC_CONVERSION[to_sanitized] __UpperCamelCase : int =1 if from_exponent > to_exponent: __UpperCamelCase : List[Any] =from_exponent - to_exponent else: __UpperCamelCase : Union[str, Any] =-(to_exponent - from_exponent) return value * pow(10 ,__A ) if __name__ == "__main__": from doctest import testmod testmod()
71
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = 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 __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() snake_case_ : List[Any] = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) snake_case_ : List[str] = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", F"""encoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append( (F"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", F"""encoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.weight""", F"""encoder.layers.{i}.fc1.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.bias""", F"""encoder.layers.{i}.fc1.bias""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.weight""", F"""encoder.layers.{i}.fc2.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.bias""", F"""encoder.layers.{i}.fc2.bias""")) rename_keys.append( (F"""transformer.encoder.layers.{i}.norm1.weight""", F"""encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm1.bias""", F"""encoder.layers.{i}.self_attn_layer_norm.bias""")) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.weight""", F"""encoder.layers.{i}.final_layer_norm.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.bias""", F"""encoder.layers.{i}.final_layer_norm.bias""")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", F"""decoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", F"""decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""", F"""decoder.layers.{i}.encoder_attn.out_proj.weight""", ) ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""", F"""decoder.layers.{i}.encoder_attn.out_proj.bias""", ) ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.weight""", F"""decoder.layers.{i}.fc1.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.bias""", F"""decoder.layers.{i}.fc1.bias""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.weight""", F"""decoder.layers.{i}.fc2.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.bias""", F"""decoder.layers.{i}.fc2.bias""")) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm1.weight""", F"""decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm1.bias""", F"""decoder.layers.{i}.self_attn_layer_norm.bias""")) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.weight""", F"""decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.bias""", F"""decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.weight""", F"""decoder.layers.{i}.final_layer_norm.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.bias""", F"""decoder.layers.{i}.final_layer_norm.bias""")) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('input_proj.weight', 'input_projection.weight'), ('input_proj.bias', 'input_projection.bias'), ('query_embed.weight', 'query_position_embeddings.weight'), ('transformer.encoder.norm.weight', 'encoder.layernorm.weight'), ('transformer.encoder.norm.bias', 'encoder.layernorm.bias'), ('transformer.decoder.norm.weight', 'decoder.layernorm.weight'), ('transformer.decoder.norm.bias', 'decoder.layernorm.bias'), ('class_embed.weight', 'class_labels_classifier.weight'), ('class_embed.bias', 'class_labels_classifier.bias'), ('bbox_embed.layers.0.weight', 'bbox_predictor.layers.0.weight'), ('bbox_embed.layers.0.bias', 'bbox_predictor.layers.0.bias'), ('bbox_embed.layers.1.weight', 'bbox_predictor.layers.1.weight'), ('bbox_embed.layers.1.bias', 'bbox_predictor.layers.1.bias'), ('bbox_embed.layers.2.weight', 'bbox_predictor.layers.2.weight'), ('bbox_embed.layers.2.bias', 'bbox_predictor.layers.2.bias'), ] ) def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Union[str, Any] = state_dict.pop(__A ) _UpperCamelCase : Tuple = val def A__ ( UpperCAmelCase_ ): _UpperCamelCase : List[str] = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: _UpperCamelCase : List[Any] = key.replace('backbone.0.body' , 'backbone.conv_encoder.model' ) _UpperCamelCase : str = value else: _UpperCamelCase : int = value return new_state_dict def A__ ( UpperCAmelCase_ ): _UpperCamelCase : Any = '' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) _UpperCamelCase : Optional[int] = state_dict.pop(f'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight' ) _UpperCamelCase : int = state_dict.pop(f'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict _UpperCamelCase : int = in_proj_weight[:2_5_6, :] _UpperCamelCase : int = in_proj_bias[:2_5_6] _UpperCamelCase : Optional[int] = in_proj_weight[2_5_6:5_1_2, :] _UpperCamelCase : str = in_proj_bias[2_5_6:5_1_2] _UpperCamelCase : List[str] = in_proj_weight[-2_5_6:, :] _UpperCamelCase : Tuple = in_proj_bias[-2_5_6:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention _UpperCamelCase : Dict = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight' ) _UpperCamelCase : Union[str, Any] = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict _UpperCamelCase : Optional[Any] = in_proj_weight[:2_5_6, :] _UpperCamelCase : List[Any] = in_proj_bias[:2_5_6] _UpperCamelCase : Union[str, Any] = in_proj_weight[2_5_6:5_1_2, :] _UpperCamelCase : str = in_proj_bias[2_5_6:5_1_2] _UpperCamelCase : Optional[Any] = in_proj_weight[-2_5_6:, :] _UpperCamelCase : int = in_proj_bias[-2_5_6:] # read in weights + bias of input projection layer of cross-attention _UpperCamelCase : List[Any] = state_dict.pop( f'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight' ) _UpperCamelCase : str = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias' ) # next, add query, keys and values (in that order) of cross-attention to the state dict _UpperCamelCase : Union[str, Any] = in_proj_weight_cross_attn[:2_5_6, :] _UpperCamelCase : Optional[Any] = in_proj_bias_cross_attn[:2_5_6] _UpperCamelCase : Tuple = in_proj_weight_cross_attn[2_5_6:5_1_2, :] _UpperCamelCase : Any = in_proj_bias_cross_attn[2_5_6:5_1_2] _UpperCamelCase : List[Any] = in_proj_weight_cross_attn[-2_5_6:, :] _UpperCamelCase : Optional[int] = in_proj_bias_cross_attn[-2_5_6:] def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase , _UpperCamelCase : Optional[Any] = image.size _UpperCamelCase : List[Any] = max(__A , __A ) _UpperCamelCase : Optional[Any] = 8_0_0 if 'detection' in checkpoint_url else 1_0_0_0 _UpperCamelCase : str = target_max_size / current_max_size _UpperCamelCase : Optional[int] = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def A__ ( UpperCAmelCase_ ): _UpperCamelCase : Dict = F.to_tensor(__A ) _UpperCamelCase : Optional[int] = F.normalize(__A , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): logger.info('Converting model...' ) # load original state dict _UpperCamelCase : List[str] = torch.hub.load_state_dict_from_url(__A , map_location='cpu' ) # rename keys for src, dest in rename_keys: rename_key(__A , __A , __A ) _UpperCamelCase : Optional[Any] = rename_backbone_keys(__A ) # query, key and value matrices need special treatment read_in_q_k_v(__A ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them _UpperCamelCase : Any = 'model.' for key in state_dict.copy().keys(): if not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ): _UpperCamelCase : Optional[int] = state_dict.pop(__A ) _UpperCamelCase : List[Any] = val # create HuggingFace model and load state dict _UpperCamelCase : Any = TableTransformerConfig( backbone='resnet18' , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: _UpperCamelCase : Tuple = 1_5 _UpperCamelCase : int = 2 _UpperCamelCase : Optional[Any] = {0: 'table', 1: 'table rotated'} _UpperCamelCase : Tuple = idalabel _UpperCamelCase : List[Any] = {v: k for k, v in idalabel.items()} else: _UpperCamelCase : str = 1_2_5 _UpperCamelCase : int = 6 _UpperCamelCase : Tuple = { 0: 'table', 1: 'table column', 2: 'table row', 3: 'table column header', 4: 'table projected row header', 5: 'table spanning cell', } _UpperCamelCase : List[str] = idalabel _UpperCamelCase : List[str] = {v: k for k, v in idalabel.items()} _UpperCamelCase : Any = DetrImageProcessor( format='coco_detection' , max_size=8_0_0 if 'detection' in checkpoint_url else 1_0_0_0 ) _UpperCamelCase : Dict = TableTransformerForObjectDetection(__A ) model.load_state_dict(__A ) model.eval() # verify our conversion _UpperCamelCase : Optional[Any] = 'example_pdf.png' if 'detection' in checkpoint_url else 'example_table.png' _UpperCamelCase : List[str] = hf_hub_download(repo_id='nielsr/example-pdf' , repo_type='dataset' , filename=__A ) _UpperCamelCase : Union[str, Any] = Image.open(__A ).convert('RGB' ) _UpperCamelCase : Tuple = normalize(resize(__A , __A ) ).unsqueeze(0 ) _UpperCamelCase : Dict = model(__A ) if "detection" in checkpoint_url: _UpperCamelCase : str = (1, 1_5, 3) _UpperCamelCase : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) _UpperCamelCase : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: _UpperCamelCase : int = (1, 1_2_5, 7) _UpperCamelCase : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) _UpperCamelCase : int = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __A , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __A , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' ) Path(__A ).mkdir(exist_ok=__A ) model.save_pretrained(__A ) image_processor.save_pretrained(__A ) if push_to_hub: # Push model to HF hub logger.info('Pushing model to the hub...' ) _UpperCamelCase : List[str] = ( 'microsoft/table-transformer-detection' if 'detection' in checkpoint_url else 'microsoft/table-transformer-structure-recognition' ) model.push_to_hub(__A ) image_processor.push_to_hub(__A ) if __name__ == "__main__": snake_case_ : List[str] = argparse.ArgumentParser() parser.add_argument( '--checkpoint_url', default='https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth', type=str, choices=[ 'https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth', 'https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth', ], help='URL of the Table Transformer checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) snake_case_ : Optional[Any] = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
83
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
def snake_case ( snake_case__ :Any = 10 , snake_case__ :str = 22) -> int: _A = range(1 , __A) _A = range(1 , __A) return sum( 1 for power in powers for base in bases if len(str(base**power)) == power) if __name__ == "__main__": print(F'''{solution(10, 22) = }''')
180
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __magic_name__ ( a__): UpperCamelCase__ = (KDPMaDiscreteScheduler,) UpperCamelCase__ = 10 def SCREAMING_SNAKE_CASE_ ( self : int , **lowercase_ : Optional[Any] ): lowercase_ : Dict = { """num_train_timesteps""": 1100, """beta_start""": 0.00_01, """beta_end""": 0.02, """beta_schedule""": """linear""", } config.update(**lowercase_ ) return config def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] , [0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Any ): lowercase_ : Dict = self.scheduler_classes[0] lowercase_ : Optional[int] = self.get_scheduler_config(prediction_type="""v_prediction""" ) lowercase_ : Tuple = scheduler_class(**lowercase_ ) scheduler.set_timesteps(self.num_inference_steps ) lowercase_ : int = self.dummy_model() lowercase_ : int = self.dummy_sample_deter * scheduler.init_noise_sigma lowercase_ : Optional[int] = sample.to(lowercase_ ) for i, t in enumerate(scheduler.timesteps ): lowercase_ : Dict = scheduler.scale_model_input(lowercase_ , lowercase_ ) lowercase_ : Optional[int] = model(lowercase_ , lowercase_ ) lowercase_ : List[str] = scheduler.step(lowercase_ , lowercase_ , lowercase_ ) lowercase_ : Tuple = output.prev_sample lowercase_ : Union[str, Any] = torch.sum(torch.abs(lowercase_ ) ) lowercase_ : Dict = torch.mean(torch.abs(lowercase_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.00_02 ) < 1E-3 def SCREAMING_SNAKE_CASE_ ( self : Tuple ): if torch_device == "mps": return lowercase_ : Dict = self.scheduler_classes[0] lowercase_ : Optional[int] = self.get_scheduler_config() lowercase_ : Optional[int] = scheduler_class(**lowercase_ ) scheduler.set_timesteps(self.num_inference_steps ) lowercase_ : int = self.dummy_model() lowercase_ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma lowercase_ : Tuple = sample.to(lowercase_ ) for i, t in enumerate(scheduler.timesteps ): lowercase_ : Any = scheduler.scale_model_input(lowercase_ , lowercase_ ) lowercase_ : str = model(lowercase_ , lowercase_ ) lowercase_ : Optional[int] = scheduler.step(lowercase_ , lowercase_ , lowercase_ ) lowercase_ : Optional[Any] = output.prev_sample lowercase_ : List[str] = torch.sum(torch.abs(lowercase_ ) ) lowercase_ : str = torch.mean(torch.abs(lowercase_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.41_25 ) < 1E-2 assert abs(result_mean.item() - 0.02_66 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.41_25 ) < 1E-2 assert abs(result_mean.item() - 0.02_66 ) < 1E-3 def SCREAMING_SNAKE_CASE_ ( self : Any ): if torch_device == "mps": return lowercase_ : Any = self.scheduler_classes[0] lowercase_ : Any = self.get_scheduler_config() lowercase_ : List[Any] = scheduler_class(**lowercase_ ) scheduler.set_timesteps(self.num_inference_steps , device=lowercase_ ) lowercase_ : Any = self.dummy_model() lowercase_ : Optional[Any] = self.dummy_sample_deter.to(lowercase_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: lowercase_ : Optional[Any] = scheduler.scale_model_input(lowercase_ , lowercase_ ) lowercase_ : List[Any] = model(lowercase_ , lowercase_ ) lowercase_ : List[Any] = scheduler.step(lowercase_ , lowercase_ , lowercase_ ) lowercase_ : Dict = output.prev_sample lowercase_ : Tuple = torch.sum(torch.abs(lowercase_ ) ) lowercase_ : Optional[Any] = torch.mean(torch.abs(lowercase_ ) ) if str(lowercase_ ).startswith("""cpu""" ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.41_25 ) < 1E-2 assert abs(result_mean.item() - 0.02_66 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.41_25 ) < 1E-2 assert abs(result_mean.item() - 0.02_66 ) < 1E-3
239
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
'''simple docstring''' import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers __SCREAMING_SNAKE_CASE : Dict = 'python tqdm regex requests packaging filelock numpy tokenizers'.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append("""dataclasses""") if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append("""importlib_metadata""") for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F'can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py') def UpperCamelCase_ ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Any=None ) -> Any: """simple docstring""" require_version(deps[pkg] , __A )
31
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py _UpperCAmelCase : Tuple = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. _UpperCAmelCase : str = direct_transformers_import(PATH_TO_TRANSFORMERS) _UpperCAmelCase : str = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` _UpperCAmelCase : List[Any] = re.compile(R"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""") _UpperCAmelCase : Dict = { 'DecisionTransformerConfig', 'EncoderDecoderConfig', 'MusicgenConfig', 'RagConfig', 'SpeechEncoderDecoderConfig', 'TimmBackboneConfig', 'VisionEncoderDecoderConfig', 'VisionTextDualEncoderConfig', 'LlamaConfig', } def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Optional[int]: lowerCamelCase__ : Optional[int] = None # source code of `config_class` lowerCamelCase__ : List[str] = inspect.getsource(__A ) lowerCamelCase__ : Tuple = _re_checkpoint.findall(__A ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith('/' ): lowerCamelCase__ : Tuple = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link lowerCamelCase__ : str = F"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: lowerCamelCase__ : Union[str, Any] = ckpt_name break return checkpoint def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: lowerCamelCase__ : List[str] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue lowerCamelCase__ : List[str] = get_checkpoint_from_config_class(__A ) lowerCamelCase__ : List[Any] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(__A ) if len(__A ) > 0: lowerCamelCase__ : List[str] = '\n'.join(sorted(__A ) ) raise ValueError(F"""The following configurations don\'t contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
50
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class __snake_case ( unittest.TestCase ): @slow def lowerCamelCase_ ( self) -> Any: '''simple docstring''' for model_name in ["bert-base-uncased"]: a__: Union[str, Any] = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Tuple = TFAutoModel.from_pretrained(lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Dict = AutoModel.from_pretrained(lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> List[Any]: '''simple docstring''' for model_name in ["bert-base-uncased"]: a__: List[str] = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Dict = TFAutoModelForPreTraining.from_pretrained(lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: str = AutoModelForPreTraining.from_pretrained(lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__: Union[str, Any] = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Optional[Any] = TFAutoModelForCausalLM.from_pretrained(lowercase , from_pt=lowercase) a__ , a__: Dict = TFAutoModelForCausalLM.from_pretrained( lowercase , output_loading_info=lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: List[Any] = AutoModelForCausalLM.from_pretrained(lowercase , from_tf=lowercase) a__ , a__: List[Any] = AutoModelForCausalLM.from_pretrained( lowercase , output_loading_info=lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> Union[str, Any]: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__: str = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Optional[Any] = TFAutoModelWithLMHead.from_pretrained(lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Any = AutoModelWithLMHead.from_pretrained(lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__: Union[str, Any] = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Union[str, Any] = TFAutoModelForMaskedLM.from_pretrained(lowercase , from_pt=lowercase) a__ , a__: Tuple = TFAutoModelForMaskedLM.from_pretrained( lowercase , output_loading_info=lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Union[str, Any] = AutoModelForMaskedLM.from_pretrained(lowercase , from_tf=lowercase) a__ , a__: List[Any] = AutoModelForMaskedLM.from_pretrained( lowercase , output_loading_info=lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> Dict: '''simple docstring''' for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__: Optional[int] = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Any = TFAutoModelForSeqaSeqLM.from_pretrained(lowercase , from_pt=lowercase) a__ , a__: Optional[int] = TFAutoModelForSeqaSeqLM.from_pretrained( lowercase , output_loading_info=lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Optional[Any] = AutoModelForSeqaSeqLM.from_pretrained(lowercase , from_tf=lowercase) a__ , a__: Optional[int] = AutoModelForSeqaSeqLM.from_pretrained( lowercase , output_loading_info=lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> int: '''simple docstring''' for model_name in ["bert-base-uncased"]: a__: Tuple = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: int = TFAutoModelForSequenceClassification.from_pretrained(lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Dict = AutoModelForSequenceClassification.from_pretrained(lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' for model_name in ["bert-base-uncased"]: a__: str = AutoConfig.from_pretrained(lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: List[Any] = TFAutoModelForQuestionAnswering.from_pretrained(lowercase , from_pt=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) a__: Any = AutoModelForQuestionAnswering.from_pretrained(lowercase , from_tf=lowercase) self.assertIsNotNone(lowercase) self.assertIsInstance(lowercase , lowercase) def lowerCamelCase_ ( self) -> Dict: '''simple docstring''' a__: Optional[Any] = TFAutoModelWithLMHead.from_pretrained(lowercase , from_pt=lowercase) self.assertIsInstance(lowercase , lowercase) self.assertEqual(model.num_parameters() , 1_44_10) self.assertEqual(model.num_parameters(only_trainable=lowercase) , 1_44_10) a__: int = AutoModelWithLMHead.from_pretrained(lowercase , from_tf=lowercase) self.assertIsInstance(lowercase , lowercase) self.assertEqual(model.num_parameters() , 1_44_10) self.assertEqual(model.num_parameters(only_trainable=lowercase) , 1_44_10) def lowerCamelCase_ ( self) -> Optional[int]: '''simple docstring''' a__: str = TFAutoModelWithLMHead.from_pretrained(lowercase , from_pt=lowercase) self.assertIsInstance(lowercase , lowercase) self.assertEqual(model.num_parameters() , 1_44_10) self.assertEqual(model.num_parameters(only_trainable=lowercase) , 1_44_10) a__: int = AutoModelWithLMHead.from_pretrained(lowercase , from_tf=lowercase) self.assertIsInstance(lowercase , lowercase) self.assertEqual(model.num_parameters() , 1_44_10) self.assertEqual(model.num_parameters(only_trainable=lowercase) , 1_44_10)
290
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _SCREAMING_SNAKE_CASE : List[str] = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class A__ ( unittest.TestCase ): """simple docstring""" def __init__( self , __snake_case , __snake_case=7 , __snake_case=3 , __snake_case=1_8 , __snake_case=3_0 , __snake_case=4_0_0 , __snake_case=None , __snake_case=True , __snake_case=True , __snake_case=None , ): snake_case = size if size is not None else {'''height''': 2_0, '''width''': 2_0} snake_case = parent snake_case = batch_size snake_case = num_channels snake_case = image_size snake_case = min_resolution snake_case = max_resolution snake_case = size snake_case = do_normalize snake_case = do_convert_rgb snake_case = [5_1_2, 1_0_2_4, 2_0_4_8, 4_0_9_6] snake_case = patch_size if patch_size is not None else {'''height''': 1_6, '''width''': 1_6} def a_ ( self ): return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def a_ ( self ): snake_case = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' snake_case = Image.open(requests.get(__snake_case , stream=__snake_case ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class A__ ( a__ , unittest.TestCase ): """simple docstring""" __magic_name__ = PixaStructImageProcessor if is_vision_available() else None def a_ ( self ): snake_case = PixaStructImageProcessingTester(self ) @property def a_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a_ ( self ): snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__snake_case , '''do_normalize''' ) ) self.assertTrue(hasattr(__snake_case , '''do_convert_rgb''' ) ) def a_ ( self ): snake_case = self.image_processor_tester.prepare_dummy_image() snake_case = self.image_processing_class(**self.image_processor_dict ) snake_case = 2_0_4_8 snake_case = image_processor(__snake_case , return_tensors='''pt''' , max_patches=__snake_case ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1E-3 , rtol=1E-3 ) ) def a_ ( self ): # Initialize image_processor snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , Image.Image ) # Test not batched input snake_case = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case = image_processor( __snake_case , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def a_ ( self ): # Initialize image_processor snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , Image.Image ) # Test not batched input snake_case = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 snake_case = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(__snake_case ): snake_case = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches snake_case = '''Hello''' snake_case = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__snake_case , header_text=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case = image_processor( __snake_case , return_tensors='''pt''' , max_patches=__snake_case , header_text=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def a_ ( self ): # Initialize image_processor snake_case = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , numpify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , np.ndarray ) snake_case = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case = image_processor( __snake_case , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def a_ ( self ): # Initialize image_processor snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , torch.Tensor ) # Test not batched input snake_case = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case = image_processor( __snake_case , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class A__ ( a__ , unittest.TestCase ): """simple docstring""" __magic_name__ = PixaStructImageProcessor if is_vision_available() else None def a_ ( self ): snake_case = PixaStructImageProcessingTester(self , num_channels=4 ) snake_case = 3 @property def a_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a_ ( self ): snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__snake_case , '''do_normalize''' ) ) self.assertTrue(hasattr(__snake_case , '''do_convert_rgb''' ) ) def a_ ( self ): # Initialize image_processor snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , Image.Image ) # Test not batched input snake_case = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case = image_processor( __snake_case , return_tensors='''pt''' , max_patches=__snake_case ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
127
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : List[str] = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
182
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class SCREAMING_SNAKE_CASE_ ( a__ ): __lowerCAmelCase = """altclip_text_model""" def __init__( self : Optional[Any] , lowerCamelCase_ : Optional[Any]=25_0002 , lowerCamelCase_ : Optional[int]=1024 , lowerCamelCase_ : Optional[int]=24 , lowerCamelCase_ : Optional[int]=16 , lowerCamelCase_ : Optional[Any]=4096 , lowerCamelCase_ : Tuple="gelu" , lowerCamelCase_ : str=0.1 , lowerCamelCase_ : Dict=0.1 , lowerCamelCase_ : Dict=514 , lowerCamelCase_ : List[str]=1 , lowerCamelCase_ : Dict=0.0_2 , lowerCamelCase_ : Dict=0.0_2 , lowerCamelCase_ : Optional[Any]=1E-05 , lowerCamelCase_ : Dict=1 , lowerCamelCase_ : Tuple=0 , lowerCamelCase_ : Dict=2 , lowerCamelCase_ : Dict="absolute" , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Optional[int]=768 , **lowerCamelCase_ : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , **lowerCamelCase_ ) UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = initializer_range UpperCamelCase = initializer_factor UpperCamelCase = layer_norm_eps UpperCamelCase = position_embedding_type UpperCamelCase = use_cache UpperCamelCase = project_dim class SCREAMING_SNAKE_CASE_ ( a__ ): __lowerCAmelCase = """altclip_vision_model""" def __init__( self : Union[str, Any] , lowerCamelCase_ : List[str]=768 , lowerCamelCase_ : Union[str, Any]=3072 , lowerCamelCase_ : Dict=512 , lowerCamelCase_ : Tuple=12 , lowerCamelCase_ : List[Any]=12 , lowerCamelCase_ : Union[str, Any]=3 , lowerCamelCase_ : str=224 , lowerCamelCase_ : List[Any]=32 , lowerCamelCase_ : Optional[int]="quick_gelu" , lowerCamelCase_ : List[Any]=1E-5 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[int]=0.0_2 , lowerCamelCase_ : Optional[int]=1.0 , **lowerCamelCase_ : List[str] , ): """simple docstring""" super().__init__(**lowerCamelCase_ ) UpperCamelCase = hidden_size UpperCamelCase = intermediate_size UpperCamelCase = projection_dim UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = num_channels UpperCamelCase = patch_size UpperCamelCase = image_size UpperCamelCase = initializer_range UpperCamelCase = initializer_factor UpperCamelCase = attention_dropout UpperCamelCase = layer_norm_eps UpperCamelCase = hidden_act @classmethod def lowerCamelCase_ ( cls : str , lowerCamelCase_ : Union[str, Any] , **lowerCamelCase_ : Optional[Any] ): """simple docstring""" cls._set_token_in_kwargs(lowerCamelCase_ ) UpperCamelCase , UpperCamelCase = cls.get_config_dict(lowerCamelCase_ , **lowerCamelCase_ ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get("""model_type""" ) == "altclip": UpperCamelCase = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCamelCase_ , **lowerCamelCase_ ) class SCREAMING_SNAKE_CASE_ ( a__ ): __lowerCAmelCase = """altclip""" __lowerCAmelCase = True def __init__( self : Union[str, Any] , lowerCamelCase_ : Any=None , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Tuple=768 , lowerCamelCase_ : str=2.6_5_9_2 , **lowerCamelCase_ : List[Any] ): """simple docstring""" UpperCamelCase = kwargs.pop("""text_config_dict""" , lowerCamelCase_ ) UpperCamelCase = kwargs.pop("""vision_config_dict""" , lowerCamelCase_ ) super().__init__(**lowerCamelCase_ ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: UpperCamelCase = {} # This is the complete result when using `text_config_dict`. UpperCamelCase = AltCLIPTextConfig(**lowerCamelCase_ ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: UpperCamelCase = ( f"""`{key}` is found in both `text_config_dict` and `text_config` but with different values. """ f"""The value `text_config_dict[\"{key}\"]` will be used instead.""" ) # If inferred from default argument values (just to be super careful) else: UpperCamelCase = ( f"""`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The """ f"""value `text_config[\"{key}\"]` will be overriden.""" ) logger.warning(lowerCamelCase_ ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: UpperCamelCase = {} # This is the complete result when using `vision_config_dict`. UpperCamelCase = AltCLIPVisionConfig(**lowerCamelCase_ ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: UpperCamelCase = { str(lowerCamelCase_ ): value for key, value in _vision_config_dict["""id2label"""].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: UpperCamelCase = ( f"""`{key}` is found in both `vision_config_dict` and `vision_config` but with different """ f"""values. The value `vision_config_dict[\"{key}\"]` will be used instead.""" ) # If inferred from default argument values (just to be super careful) else: UpperCamelCase = ( f"""`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. """ f"""The value `vision_config[\"{key}\"]` will be overriden.""" ) logger.warning(lowerCamelCase_ ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: UpperCamelCase = {} logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""" ) if vision_config is None: UpperCamelCase = {} logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""" ) UpperCamelCase = AltCLIPTextConfig(**lowerCamelCase_ ) UpperCamelCase = AltCLIPVisionConfig(**lowerCamelCase_ ) UpperCamelCase = projection_dim UpperCamelCase = logit_scale_init_value UpperCamelCase = 1.0 @classmethod def lowerCamelCase_ ( cls : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , **lowerCamelCase_ : Union[str, Any] ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) UpperCamelCase = self.text_config.to_dict() UpperCamelCase = self.vision_config.to_dict() UpperCamelCase = self.__class__.model_type return output
343
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): 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 , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class _snake_case : def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : str=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=False ,SCREAMING_SNAKE_CASE__ : Optional[Any]=10 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 ,SCREAMING_SNAKE_CASE__ : List[Any]=32 * 4 ,SCREAMING_SNAKE_CASE__ : Dict=32 * 6 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=32 ,): SCREAMING_SNAKE_CASE:Any = parent SCREAMING_SNAKE_CASE:str = batch_size SCREAMING_SNAKE_CASE:str = is_training SCREAMING_SNAKE_CASE:Optional[Any] = use_auxiliary_loss SCREAMING_SNAKE_CASE:Tuple = num_queries SCREAMING_SNAKE_CASE:Any = num_channels SCREAMING_SNAKE_CASE:Optional[int] = min_size SCREAMING_SNAKE_CASE:Dict = max_size SCREAMING_SNAKE_CASE:str = num_labels SCREAMING_SNAKE_CASE:Union[str, Any] = mask_feature_size def __UpperCamelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE:Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Any = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Optional[int] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=SCREAMING_SNAKE_CASE__ ) > 0.5 ).float() SCREAMING_SNAKE_CASE:List[str] = (torch.rand((self.batch_size, self.num_labels) ,device=SCREAMING_SNAKE_CASE__ ) > 0.5).long() SCREAMING_SNAKE_CASE:int = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __UpperCamelCase ( self : Union[str, Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] ,) ,decoder_config=DetrConfig( decoder_ffn_dim=128 ,num_queries=self.num_queries ,decoder_attention_heads=2 ,d_model=self.mask_feature_size ,) ,mask_feature_size=self.mask_feature_size ,fpn_feature_size=self.mask_feature_size ,num_channels=self.num_channels ,num_labels=self.num_labels ,) def __UpperCamelCase ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:str = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE:List[Any] = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def __UpperCamelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ): SCREAMING_SNAKE_CASE:Any = output.encoder_hidden_states SCREAMING_SNAKE_CASE:Tuple = output.pixel_decoder_hidden_states SCREAMING_SNAKE_CASE:int = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE__ ) ,config.decoder_config.decoder_layers ) def __UpperCamelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : List[Any]=False ): with torch.no_grad(): SCREAMING_SNAKE_CASE:Optional[Any] = MaskFormerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() SCREAMING_SNAKE_CASE:Optional[Any] = model(pixel_values=SCREAMING_SNAKE_CASE__ ,pixel_mask=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.mask_feature_size) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tuple ): SCREAMING_SNAKE_CASE:Dict = MaskFormerForInstanceSegmentation(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE__ : Optional[int] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): SCREAMING_SNAKE_CASE:List[str] = model(pixel_values=SCREAMING_SNAKE_CASE__ ,pixel_mask=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Any = model(SCREAMING_SNAKE_CASE__ ) comm_check_on_output(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:int = model( pixel_values=SCREAMING_SNAKE_CASE__ ,pixel_mask=SCREAMING_SNAKE_CASE__ ,mask_labels=SCREAMING_SNAKE_CASE__ ,class_labels=SCREAMING_SNAKE_CASE__ ) comm_check_on_output(SCREAMING_SNAKE_CASE__ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class _snake_case ( a__ , a__ , unittest.TestCase ): _A : str = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () _A : int = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) _A : str = False _A : Any = False _A : List[str] = False _A : Optional[int] = False def __UpperCamelCase ( self : int ): SCREAMING_SNAKE_CASE:Dict = MaskFormerModelTester(self ) SCREAMING_SNAKE_CASE:Union[str, Any] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : int ): self.config_tester.run_common_tests() def __UpperCamelCase ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE:List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def __UpperCamelCase ( self : Optional[Any] ): pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def __UpperCamelCase ( self : Optional[Any] ): pass @unittest.skip(reason="MaskFormer is not a generative model" ) def __UpperCamelCase ( self : Optional[Any] ): pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def __UpperCamelCase ( self : Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def __UpperCamelCase ( self : Optional[int] ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __UpperCamelCase ( self : int ): pass def __UpperCamelCase ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE:Any = model_class(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE:Union[str, Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE:str = ["pixel_values"] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__ ) @slow def __UpperCamelCase ( self : Any ): for model_name in ["facebook/maskformer-swin-small-coco"]: SCREAMING_SNAKE_CASE:str = MaskFormerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE:Union[str, Any] = (self.model_tester.min_size,) * 2 SCREAMING_SNAKE_CASE:str = { "pixel_values": torch.randn((2, 3, *size) ,device=SCREAMING_SNAKE_CASE__ ), "mask_labels": torch.randn((2, 10, *size) ,device=SCREAMING_SNAKE_CASE__ ), "class_labels": torch.zeros(2 ,10 ,device=SCREAMING_SNAKE_CASE__ ).long(), } SCREAMING_SNAKE_CASE:List[Any] = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) self.assertTrue(outputs.loss is not None ) def __UpperCamelCase ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE:List[Any] = model_class(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Dict = model(**SCREAMING_SNAKE_CASE__ ,output_attentions=SCREAMING_SNAKE_CASE__ ) self.assertTrue(outputs.attentions is not None ) def __UpperCamelCase ( self : Any ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss SCREAMING_SNAKE_CASE:str = self.all_model_classes[1] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:Union[str, Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE:List[Any] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.train() SCREAMING_SNAKE_CASE:Tuple = model(SCREAMING_SNAKE_CASE__ ,mask_labels=SCREAMING_SNAKE_CASE__ ,class_labels=SCREAMING_SNAKE_CASE__ ).loss loss.backward() def __UpperCamelCase ( self : List[str] ): # only MaskFormerForInstanceSegmentation has the loss SCREAMING_SNAKE_CASE:Tuple = self.all_model_classes[1] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:str = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE:List[str] = True SCREAMING_SNAKE_CASE:Optional[Any] = True SCREAMING_SNAKE_CASE:Union[str, Any] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.train() SCREAMING_SNAKE_CASE:Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,mask_labels=SCREAMING_SNAKE_CASE__ ,class_labels=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() SCREAMING_SNAKE_CASE:Optional[int] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't SCREAMING_SNAKE_CASE:Union[str, Any] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() SCREAMING_SNAKE_CASE:Dict = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) A_ = 1e-4 def A_ ( ): SCREAMING_SNAKE_CASE:List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class _snake_case ( unittest.TestCase ): @cached_property def __UpperCamelCase ( self : List[str] ): return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def __UpperCamelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE:List[Any] = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Any = self.default_image_processor SCREAMING_SNAKE_CASE:Tuple = prepare_img() SCREAMING_SNAKE_CASE:List[str] = image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Tuple = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE__ ,(1, 3, 800, 1_088) ) with torch.no_grad(): SCREAMING_SNAKE_CASE:List[Any] = model(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[Any] = torch.tensor( [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE:str = torch.tensor( [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE:List[str] = torch.tensor( [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ) ) def __UpperCamelCase ( self : int ): SCREAMING_SNAKE_CASE:Dict = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(SCREAMING_SNAKE_CASE__ ) .eval() ) SCREAMING_SNAKE_CASE:Optional[Any] = self.default_image_processor SCREAMING_SNAKE_CASE:Tuple = prepare_img() SCREAMING_SNAKE_CASE:Dict = image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[Any] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE__ ,(1, 3, 800, 1_088) ) with torch.no_grad(): SCREAMING_SNAKE_CASE:Union[str, Any] = model(**SCREAMING_SNAKE_CASE__ ) # masks_queries_logits SCREAMING_SNAKE_CASE:Dict = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ,) SCREAMING_SNAKE_CASE:Optional[Any] = [ [-1.3_737_124, -1.7_724_937, -1.9_364_233], [-1.5_977_281, -1.9_867_939, -2.1_523_695], [-1.5_795_398, -1.9_269_832, -2.093_942], ] SCREAMING_SNAKE_CASE:Dict = torch.tensor(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ) ) # class_queries_logits SCREAMING_SNAKE_CASE:int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape ,(1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) SCREAMING_SNAKE_CASE:Optional[Any] = torch.tensor( [ [1.6_512e00, -5.2_572e00, -3.3_519e00], [3.6_169e-02, -5.9_025e00, -2.9_313e00], [1.0_766e-04, -7.7_630e00, -5.1_263e00], ] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ) ) def __UpperCamelCase ( self : Dict ): SCREAMING_SNAKE_CASE:str = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(SCREAMING_SNAKE_CASE__ ) .eval() ) SCREAMING_SNAKE_CASE:Union[str, Any] = self.default_image_processor SCREAMING_SNAKE_CASE:Any = prepare_img() SCREAMING_SNAKE_CASE:str = image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Dict = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE__ ,(1, 3, 800, 1_088) ) with torch.no_grad(): SCREAMING_SNAKE_CASE:Optional[Any] = model(**SCREAMING_SNAKE_CASE__ ) # masks_queries_logits SCREAMING_SNAKE_CASE:List[str] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ,) SCREAMING_SNAKE_CASE:Optional[int] = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]] SCREAMING_SNAKE_CASE:List[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ) ) # class_queries_logits SCREAMING_SNAKE_CASE:Dict = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape ,(1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) SCREAMING_SNAKE_CASE:Optional[int] = torch.tensor( [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ) ) def __UpperCamelCase ( self : str ): SCREAMING_SNAKE_CASE:str = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(SCREAMING_SNAKE_CASE__ ) .eval() ) SCREAMING_SNAKE_CASE:int = self.default_image_processor SCREAMING_SNAKE_CASE:int = image_processor( [np.zeros((3, 800, 1_333) ), np.zeros((3, 800, 1_333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors="pt" ,) SCREAMING_SNAKE_CASE:Union[str, Any] = inputs["pixel_values"].to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Optional[int] = [el.to(SCREAMING_SNAKE_CASE__ ) for el in inputs["mask_labels"]] SCREAMING_SNAKE_CASE:Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE__ ) for el in inputs["class_labels"]] with torch.no_grad(): SCREAMING_SNAKE_CASE:List[Any] = model(**SCREAMING_SNAKE_CASE__ ) self.assertTrue(outputs.loss is not None )
139
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): 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 token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
def A ( a_ ) -> list: __UpperCamelCase : Optional[Any] =len(__A ) for i in range(1 ,__A ): __UpperCamelCase : Any =collection[i] __UpperCamelCase : Tuple =0 __UpperCamelCase : Union[str, Any] =i - 1 while low <= high: __UpperCamelCase : Optional[Any] =(low + high) // 2 if val < collection[mid]: __UpperCamelCase : Tuple =mid - 1 else: __UpperCamelCase : str =mid + 1 for j in range(__A ,__A ,-1 ): __UpperCamelCase : List[Any] =collection[j - 1] __UpperCamelCase : Tuple =val return collection if __name__ == "__main__": A_ :Tuple = input('''Enter numbers separated by a comma:\n''').strip() A_ :str = [int(item) for item in user_input.split(''',''')] print(binary_insertion_sort(unsorted))
71
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
'''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 rescale, resize, to_channel_dimension_format from ...image_utils import ( 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 snake_case_ : Optional[int] = logging.get_logger(__name__) def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : List[str] = b.T _UpperCamelCase : Optional[Any] = np.sum(np.square(__A ) , axis=1 ) _UpperCamelCase : Tuple = np.sum(np.square(__A ) , axis=0 ) _UpperCamelCase : Dict = np.matmul(__A , __A ) _UpperCamelCase : Dict = aa[:, None] - 2 * ab + ba[None, :] return d def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Optional[Any] = x.reshape(-1 , 3 ) _UpperCamelCase : int = squared_euclidean_distance(__A , __A ) return np.argmin(__A , axis=1 ) class lowercase__ ( a__ ): lowercase__ = ["""pixel_values"""] def __init__( self : int ,lowerCamelCase__ : int = None ,lowerCamelCase__ : Optional[int] = True ,lowerCamelCase__ : str = None ,lowerCamelCase__ : int = PILImageResampling.BILINEAR ,lowerCamelCase__ : int = True ,lowerCamelCase__ : Optional[Any] = True ,**lowerCamelCase__ : str ,): '''simple docstring''' super().__init__(**lowerCamelCase__ ) _UpperCamelCase : List[str] = size if size is not None else {'height': 256, 'width': 256} _UpperCamelCase : Union[str, Any] = get_size_dict(lowerCamelCase__ ) _UpperCamelCase : Any = np.array(lowerCamelCase__ ) if clusters is not None else None _UpperCamelCase : Any = do_resize _UpperCamelCase : List[Any] = size _UpperCamelCase : List[Any] = resample _UpperCamelCase : str = do_normalize _UpperCamelCase : Optional[Any] = do_color_quantize def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : int = PILImageResampling.BILINEAR ,lowerCamelCase__ : Tuple = None ,**lowerCamelCase__ : Any ,): '''simple docstring''' _UpperCamelCase : List[str] = get_size_dict(lowerCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(F'Size dictionary must contain both height and width keys. Got {size.keys()}' ) return resize( lowerCamelCase__ ,size=(size['height'], size['width']) ,resample=lowerCamelCase__ ,data_format=lowerCamelCase__ ,**lowerCamelCase__ ) def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : str = None ,): '''simple docstring''' _UpperCamelCase : str = rescale(image=lowerCamelCase__ ,scale=1 / 1_2_7.5 ,data_format=lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = image - 1 return image def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[str] = None ,lowerCamelCase__ : str = None ,lowerCamelCase__ : Union[str, Any] = None ,lowerCamelCase__ : Tuple = None ,lowerCamelCase__ : str = None ,lowerCamelCase__ : Dict = None ,lowerCamelCase__ : List[Any] = None ,lowerCamelCase__ : Dict = ChannelDimension.FIRST ,**lowerCamelCase__ : Optional[int] ,): '''simple docstring''' _UpperCamelCase : List[Any] = do_resize if do_resize is not None else self.do_resize _UpperCamelCase : Dict = size if size is not None else self.size _UpperCamelCase : List[Any] = get_size_dict(lowerCamelCase__ ) _UpperCamelCase : Dict = resample if resample is not None else self.resample _UpperCamelCase : Tuple = do_normalize if do_normalize is not None else self.do_normalize _UpperCamelCase : Optional[int] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize _UpperCamelCase : Any = clusters if clusters is not None else self.clusters _UpperCamelCase : Union[str, Any] = np.array(lowerCamelCase__ ) _UpperCamelCase : Tuple = make_list_of_images(lowerCamelCase__ ) if not valid_images(lowerCamelCase__ ): 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_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. _UpperCamelCase : int = [to_numpy_array(lowerCamelCase__ ) for image in images] if do_resize: _UpperCamelCase : List[Any] = [self.resize(image=lowerCamelCase__ ,size=lowerCamelCase__ ,resample=lowerCamelCase__ ) for image in images] if do_normalize: _UpperCamelCase : Union[str, Any] = [self.normalize(image=lowerCamelCase__ ) for image in images] if do_color_quantize: _UpperCamelCase : Any = [to_channel_dimension_format(lowerCamelCase__ ,ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) _UpperCamelCase : Dict = np.array(lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = color_quantize(lowerCamelCase__ ,lowerCamelCase__ ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) _UpperCamelCase : Union[str, Any] = images.shape[0] _UpperCamelCase : List[str] = images.reshape(lowerCamelCase__ ,-1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. _UpperCamelCase : Optional[int] = list(lowerCamelCase__ ) else: _UpperCamelCase : Union[str, Any] = [to_channel_dimension_format(lowerCamelCase__ ,lowerCamelCase__ ) for image in images] _UpperCamelCase : List[Any] = {'input_ids': images} return BatchFeature(data=lowerCamelCase__ ,tensor_type=lowerCamelCase__ )
83
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
def snake_case ( snake_case__ :Dict , snake_case__ :Union[str, Any] , snake_case__ :int) -> bool: return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(__A)) def snake_case ( snake_case__ :Optional[int] , snake_case__ :str , snake_case__ :Union[str, Any] , snake_case__ :Optional[int]) -> bool: if index == len(__A): return True # Recursive Step for i in range(__A): if valid_coloring(graph[index] , __A , __A): # Color current vertex _A = i # Validate coloring if util_color(__A , __A , __A , index + 1): return True # Backtrack _A = -1 return False def snake_case ( snake_case__ :List[str] , snake_case__ :Dict) -> list[int]: _A = [-1] * len(__A) if util_color(__A , __A , __A , 0): return colored_vertices return []
180
'''simple docstring''' # Copyright 2021 The HuggingFace 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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
'''simple docstring''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase ( ) -> List[Any]: lowercase_ : Union[str, Any] = """https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg""" lowercase_ : str = Image.open(requests.get(__A , stream=__A ).raw ).convert("""RGB""" ) return image def lowerCamelCase ( UpperCAmelCase__ : Optional[int] ) -> List[str]: lowercase_ : List[str] = [] # fmt: off # vision encoder rename_keys.append(("""visual_encoder.cls_token""", """vision_model.embeddings.class_embedding""") ) rename_keys.append(("""visual_encoder.pos_embed""", """vision_model.embeddings.position_embedding""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.weight""", """vision_model.embeddings.patch_embedding.weight""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.bias""", """vision_model.embeddings.patch_embedding.bias""") ) rename_keys.append(("""ln_vision.weight""", """vision_model.post_layernorm.weight""") ) rename_keys.append(("""ln_vision.bias""", """vision_model.post_layernorm.bias""") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.weight""", """qformer.embeddings.layernorm.weight""") ) rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.bias""", """qformer.embeddings.layernorm.bias""") ) # fmt: on return rename_keys def lowerCamelCase ( UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> int: lowercase_ : Dict = dct.pop(__A ) lowercase_ : Optional[Any] = val def lowerCamelCase ( UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any ) -> Optional[Any]: for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases lowercase_ : Tuple = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) lowercase_ : List[Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict lowercase_ : List[Any] = torch.cat((q_bias, torch.zeros_like(__A , requires_grad=__A ), v_bias) ) lowercase_ : Optional[Any] = qkv_bias def lowerCamelCase ( UpperCAmelCase__ : int ) -> Dict: lowercase_ : Dict = 364 if """coco""" in model_name else 224 lowercase_ : Optional[int] = InstructBlipVisionConfig(image_size=__A ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: lowercase_ : List[str] = TaConfig.from_pretrained("""google/flan-t5-xl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: lowercase_ : int = TaConfig.from_pretrained("""google/flan-t5-xxl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: lowercase_ : Tuple = LlamaConfig.from_pretrained("""decapoda-research/llama-7b-hf""" , vocab_size=32001 ).to_dict() elif "vicuna-13b" in model_name: lowercase_ : Optional[Any] = LlamaConfig.from_pretrained("""decapoda-research/llama-13b-hf""" , vocab_size=32001 ).to_dict() else: raise ValueError("""Model name not supported""" ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 lowercase_ : str = InstructBlipQFormerConfig(vocab_size=30523 ).to_dict() lowercase_ : str = InstructBlipConfig(vision_config=__A , text_config=__A , qformer_config=__A ) return config, image_size @torch.no_grad() def lowerCamelCase ( UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : int=False ) -> Optional[int]: lowercase_ : Dict = AutoTokenizer.from_pretrained("""bert-base-uncased""" , truncation_side="""left""" ) qformer_tokenizer.add_special_tokens({"""bos_token""": """[DEC]"""} ) if "t5" in model_name: lowercase_ : Any = TaTokenizerFast.from_pretrained("""google/flan-t5-xl""" , truncation_side="""left""" ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) lowercase_ : Tuple = LlamaTokenizerFast.from_pretrained( """huggyllama/llama-7b""" , truncation_side="""left""" , bos_token="""</s>""" , unk_token="""</s>""" ) tokenizer.add_special_tokens({"""pad_token""": """[PAD]"""} ) lowercase_ , lowercase_ : List[Any] = get_blipa_config(__A ) lowercase_ : Union[str, Any] = InstructBlipForConditionalGeneration(__A ).eval() lowercase_ : List[Any] = { """instructblip-vicuna-7b""": ("""blip2_vicuna_instruct""", """vicuna7b"""), """instructblip-vicuna-13b""": ("""blip2_vicuna_instruct""", """vicuna13b"""), """instructblip-flan-t5-xl""": ("""blip2_t5_instruct""", """flant5xl"""), """instructblip-flan-t5-xxl""": ("""blip2_t5_instruct""", """flant5xxl"""), } lowercase_ , lowercase_ : Optional[int] = model_name_to_original[model_name] # load original model print("""Loading original model...""" ) lowercase_ : List[str] = """cuda:1""" if torch.cuda.is_available() else """cpu""" lowercase_ : Optional[Any] = """cuda:2""" if torch.cuda.is_available() else """cpu""" lowercase_ , lowercase_ , lowercase_ : Optional[int] = load_model_and_preprocess( name=__A , model_type=__A , is_eval=__A , device=__A ) original_model.eval() print("""Done!""" ) # update state dict keys lowercase_ : List[Any] = original_model.state_dict() lowercase_ : Any = create_rename_keys(__A ) for src, dest in rename_keys: rename_key(__A , __A , __A ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): lowercase_ : Union[str, Any] = state_dict.pop(__A ) if key.startswith("""Qformer.bert""" ): lowercase_ : int = key.replace("""Qformer.bert""" , """qformer""" ) if "attention.self" in key: lowercase_ : int = key.replace("""self""" , """attention""" ) if "llm_proj" in key: lowercase_ : str = key.replace("""llm_proj""" , """language_projection""" ) if "t5_proj" in key: lowercase_ : Optional[Any] = key.replace("""t5_proj""" , """language_projection""" ) if key.startswith("""llm_model""" ): lowercase_ : List[str] = key.replace("""llm_model""" , """language_model""" ) if key.startswith("""t5""" ): lowercase_ : Optional[int] = key.replace("""t5""" , """language""" ) lowercase_ : Any = val # read in qv biases read_in_q_v_bias(__A , __A ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(__A , strict=__A ) lowercase_ : str = load_demo_image() lowercase_ : str = """What is unusual about this image?""" # create processor lowercase_ : int = BlipImageProcessor( size={"""height""": image_size, """width""": image_size} , image_mean=__A , image_std=__A ) lowercase_ : Optional[Any] = InstructBlipProcessor( image_processor=__A , tokenizer=__A , qformer_tokenizer=__A , ) lowercase_ : Optional[int] = processor(images=__A , text=__A , return_tensors="""pt""" ).to(__A ) # make sure processor creates exact same pixel values lowercase_ : str = vis_processors["""eval"""](__A ).unsqueeze(0 ).to(__A ) lowercase_ : Tuple = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ) , __A ) original_model.to(__A ) hf_model.to(__A ) with torch.no_grad(): if "vicuna" in model_name: lowercase_ : List[str] = original_model({"""image""": original_pixel_values, """text_input""": [prompt]} ).logits lowercase_ : str = hf_model(**__A ).logits else: lowercase_ : Union[str, Any] = original_model( {"""image""": original_pixel_values, """text_input""": [prompt], """text_output""": ["""\n"""]} ).logits lowercase_ : Tuple = tokenizer("""\n""" , return_tensors="""pt""" ).input_ids.to(__A ) lowercase_ : Union[str, Any] = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100 ) lowercase_ : Tuple = hf_model(**__A , labels=__A ).logits print("""First values of original logits:""" , original_logits[0, :3, :3] ) print("""First values of HF logits:""" , logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape lowercase_ : Any = 1e-4 if """vicuna""" in model_name else 1e-5 assert torch.allclose(original_logits.to(logits.device ) , __A , atol=__A ) print("""Looks ok!""" ) print("""Generating with original model...""" ) lowercase_ : Optional[int] = original_model.generate({"""image""": original_pixel_values, """prompt""": prompt} , num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print("""Generating with HF model...""" ) lowercase_ : int = hf_model.generate( **__A , do_sample=__A , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? lowercase_ : List[str] = 2 print("""Original generation:""" , __A ) lowercase_ : Dict = processor.batch_decode(__A , skip_special_tokens=__A ) lowercase_ : Any = [text.strip() for text in output_text] print("""HF generation:""" , __A ) if pytorch_dump_folder_path is not None: processor.save_pretrained(__A ) hf_model.save_pretrained(__A ) if push_to_hub: processor.push_to_hub(F'''Salesforce/{model_name}''' ) hf_model.push_to_hub(F'''Salesforce/{model_name}''' ) if __name__ == "__main__": _lowercase : int = argparse.ArgumentParser() _lowercase : int = [ 'instructblip-vicuna-7b', 'instructblip-vicuna-13b', 'instructblip-flan-t5-xl', 'instructblip-flan-t5-xxl', ] parser.add_argument( "--model_name", default="instructblip-flan-t5-xl", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) _lowercase : int = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
239
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
'''simple docstring''' from __future__ import annotations def UpperCamelCase_ ( _UpperCAmelCase : Optional[int] ) -> bool: """simple docstring""" _UpperCAmelCase : List[Any] = str(__A ) return n == n[::-1] def UpperCamelCase_ ( _UpperCAmelCase : Any = 1_000_000 ) -> Tuple: """simple docstring""" _UpperCAmelCase : Any = 0 for i in range(1 , __A ): if is_palindrome(__A ) and is_palindrome(bin(__A ).split("b" )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
31
'''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 ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\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 , *a , **a ): 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. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = 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. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = 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']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} 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`" ) UpperCamelCase__ = 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`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = 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." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments 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 , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = 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: UpperCamelCase__ = 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" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = 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. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "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: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "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 UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = 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 __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = 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: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def SCREAMING_SNAKE_CASE ( ) -> Any: lowerCamelCase__ : List[Any] = ArgumentParser('Accelerate CLI tool' , usage='accelerate <command> [<args>]' , allow_abbrev=__A ) lowerCamelCase__ : int = parser.add_subparsers(help='accelerate command helpers' ) # Register commands get_config_parser(subparsers=__A ) env_command_parser(subparsers=__A ) launch_command_parser(subparsers=__A ) tpu_command_parser(subparsers=__A ) test_command_parser(subparsers=__A ) # Let's go lowerCamelCase__ : Optional[int] = parser.parse_args() if not hasattr(__A , 'func' ): parser.print_help() exit(1 ) # Run args.func(__A ) if __name__ == "__main__": main()
50
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
"""simple docstring""" import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class __snake_case ( a__ , a__ ): @register_to_config def __init__( self , lowercase = 1_28 , lowercase = 2_56 , lowercase = 2000.0 , lowercase = 7_68 , lowercase = 12 , lowercase = 12 , lowercase = 64 , lowercase = 20_48 , lowercase = 0.1 , ) -> Optional[Any]: '''simple docstring''' super().__init__() a__: Union[str, Any] = nn.Sequential( nn.Linear(lowercase , d_model * 4 , bias=lowercase) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=lowercase) , nn.SiLU() , ) a__: Optional[Any] = nn.Embedding(lowercase , lowercase) a__: Union[str, Any] = False a__: int = nn.Linear(lowercase , lowercase , bias=lowercase) a__: Optional[Any] = nn.Dropout(p=lowercase) a__: Optional[Any] = nn.ModuleList() for lyr_num in range(lowercase): # FiLM conditional T5 decoder a__: int = DecoderLayer(d_model=lowercase , d_kv=lowercase , num_heads=lowercase , d_ff=lowercase , dropout_rate=lowercase) self.decoders.append(lowercase) a__: Tuple = TaLayerNorm(lowercase) a__: List[Any] = nn.Dropout(p=lowercase) a__: Tuple = nn.Linear(lowercase , lowercase , bias=lowercase) def lowerCamelCase_ ( self , lowercase , lowercase) -> List[str]: '''simple docstring''' a__: int = torch.mul(query_input.unsqueeze(-1) , key_input.unsqueeze(-2)) return mask.unsqueeze(-3) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__ , a__ , a__: Tuple = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. a__: Optional[int] = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype) a__: Optional[int] = self.conditioning_emb(lowercase).unsqueeze(1) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) a__: int = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. a__: Optional[int] = torch.broadcast_to( torch.arange(lowercase , device=decoder_input_tokens.device) , (batch, seq_length) , ) a__: List[Any] = self.position_encoding(lowercase) a__: Tuple = self.continuous_inputs_projection(lowercase) inputs += position_encodings a__: List[Any] = self.dropout(lowercase) # decoder: No padding present. a__: List[str] = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype) # Translate encoding masks to encoder-decoder masks. a__: List[str] = [(x, self.encoder_decoder_mask(lowercase , lowercase)) for x, y in encodings_and_masks] # cross attend style: concat encodings a__: str = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1) a__: Optional[int] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1) for lyr in self.decoders: a__: List[str] = lyr( lowercase , conditioning_emb=lowercase , encoder_hidden_states=lowercase , encoder_attention_mask=lowercase , )[0] a__: str = self.decoder_norm(lowercase) a__: Optional[int] = self.post_dropout(lowercase) a__: int = self.spec_out(lowercase) return spec_out class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase=1e-6) -> Optional[Any]: '''simple docstring''' super().__init__() a__: List[str] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=lowercase , d_kv=lowercase , num_heads=lowercase , dropout_rate=lowercase)) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=lowercase , d_kv=lowercase , num_heads=lowercase , dropout_rate=lowercase , layer_norm_epsilon=lowercase , )) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=lowercase , d_ff=lowercase , dropout_rate=lowercase , layer_norm_epsilon=lowercase)) def lowerCamelCase_ ( self , lowercase , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , ) -> str: '''simple docstring''' a__: Optional[int] = self.layer[0]( lowercase , conditioning_emb=lowercase , attention_mask=lowercase , ) if encoder_hidden_states is not None: a__: Union[str, Any] = torch.where(encoder_attention_mask > 0 , 0 , -1e10).to( encoder_hidden_states.dtype) a__: List[str] = self.layer[1]( lowercase , key_value_states=lowercase , attention_mask=lowercase , ) # Apply Film Conditional Feed Forward layer a__: List[Any] = self.layer[-1](lowercase , lowercase) return (hidden_states,) class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' super().__init__() a__: Tuple = TaLayerNorm(lowercase) a__: int = TaFiLMLayer(in_features=d_model * 4 , out_features=lowercase) a__: List[str] = Attention(query_dim=lowercase , heads=lowercase , dim_head=lowercase , out_bias=lowercase , scale_qk=lowercase) a__: str = nn.Dropout(lowercase) def lowerCamelCase_ ( self , lowercase , lowercase=None , lowercase=None , ) -> Optional[Any]: '''simple docstring''' a__: Any = self.layer_norm(lowercase) if conditioning_emb is not None: a__: Tuple = self.FiLMLayer(lowercase , lowercase) # Self-attention block a__: Dict = self.attention(lowercase) a__: Optional[Any] = hidden_states + self.dropout(lowercase) return hidden_states class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase) -> Optional[int]: '''simple docstring''' super().__init__() a__: Optional[Any] = Attention(query_dim=lowercase , heads=lowercase , dim_head=lowercase , out_bias=lowercase , scale_qk=lowercase) a__: Any = TaLayerNorm(lowercase , eps=lowercase) a__: int = nn.Dropout(lowercase) def lowerCamelCase_ ( self , lowercase , lowercase=None , lowercase=None , ) -> Tuple: '''simple docstring''' a__: List[str] = self.layer_norm(lowercase) a__: Optional[Any] = self.attention( lowercase , encoder_hidden_states=lowercase , attention_mask=attention_mask.squeeze(1) , ) a__: Optional[int] = hidden_states + self.dropout(lowercase) return layer_output class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase) -> Tuple: '''simple docstring''' super().__init__() a__: str = TaDenseGatedActDense(d_model=lowercase , d_ff=lowercase , dropout_rate=lowercase) a__: Tuple = TaFiLMLayer(in_features=d_model * 4 , out_features=lowercase) a__: Any = TaLayerNorm(lowercase , eps=lowercase) a__: Optional[Any] = nn.Dropout(lowercase) def lowerCamelCase_ ( self , lowercase , lowercase=None) -> Dict: '''simple docstring''' a__: Optional[Any] = self.layer_norm(lowercase) if conditioning_emb is not None: a__: Optional[int] = self.film(lowercase , lowercase) a__: Optional[int] = self.DenseReluDense(lowercase) a__: Optional[int] = hidden_states + self.dropout(lowercase) return hidden_states class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase) -> List[Any]: '''simple docstring''' super().__init__() a__: Tuple = nn.Linear(lowercase , lowercase , bias=lowercase) a__: List[Any] = nn.Linear(lowercase , lowercase , bias=lowercase) a__: Optional[Any] = nn.Linear(lowercase , lowercase , bias=lowercase) a__: List[str] = nn.Dropout(lowercase) a__: List[Any] = NewGELUActivation() def lowerCamelCase_ ( self , lowercase) -> Any: '''simple docstring''' a__: Optional[int] = self.act(self.wi_a(lowercase)) a__: Tuple = self.wi_a(lowercase) a__: Union[str, Any] = hidden_gelu * hidden_linear a__: Union[str, Any] = self.dropout(lowercase) a__: Optional[int] = self.wo(lowercase) return hidden_states class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase=1e-6) -> int: '''simple docstring''' super().__init__() a__: Optional[int] = nn.Parameter(torch.ones(lowercase)) a__: Dict = eps def lowerCamelCase_ ( self , lowercase) -> str: '''simple docstring''' a__: List[Any] = hidden_states.to(torch.floataa).pow(2).mean(-1 , keepdim=lowercase) a__: Dict = hidden_states * torch.rsqrt(variance + self.variance_epsilon) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: a__: List[Any] = hidden_states.to(self.weight.dtype) return self.weight * hidden_states class __snake_case ( nn.Module ): def lowerCamelCase_ ( self , lowercase) -> int: '''simple docstring''' return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(lowercase , 3.0)))) class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase) -> Dict: '''simple docstring''' super().__init__() a__: Optional[Any] = nn.Linear(lowercase , out_features * 2 , bias=lowercase) def lowerCamelCase_ ( self , lowercase , lowercase) -> Dict: '''simple docstring''' a__: Optional[Any] = self.scale_bias(lowercase) a__ , a__: Tuple = torch.chunk(lowercase , 2 , -1) a__: Tuple = x * (1 + scale) + shift return x
290
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A__ ( a__ , unittest.TestCase ): """simple docstring""" __magic_name__ = OpenAIGPTTokenizer __magic_name__ = OpenAIGPTTokenizerFast __magic_name__ = True __magic_name__ = False def a_ ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case = [ '''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>''', ] snake_case = dict(zip(__snake_case , range(len(__snake_case ) ) ) ) snake_case = ['''#version: 0.2''', '''l o''', '''lo w''', '''e r</w>''', ''''''] snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(__snake_case ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(__snake_case ) ) def a_ ( self , __snake_case ): return "lower newer", "lower newer" def a_ ( self ): snake_case = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) snake_case = '''lower''' snake_case = ['''low''', '''er</w>'''] snake_case = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) snake_case = tokens + ['''<unk>'''] snake_case = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , __snake_case ) def a_ ( self , __snake_case=1_5 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): snake_case = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) # Simple input snake_case = '''This is a simple input''' snake_case = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case = ('''This is a simple input''', '''This is a pair''') snake_case = [ ('''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(__snake_case , tokenizer_r.encode , __snake_case , max_length=__snake_case , padding='''max_length''' ) # Simple input self.assertRaises(__snake_case , tokenizer_r.encode_plus , __snake_case , max_length=__snake_case , padding='''max_length''' ) # Simple input self.assertRaises( __snake_case , tokenizer_r.batch_encode_plus , __snake_case , max_length=__snake_case , padding='''max_length''' , ) # Pair input self.assertRaises(__snake_case , tokenizer_r.encode , __snake_case , max_length=__snake_case , padding='''max_length''' ) # Pair input self.assertRaises(__snake_case , tokenizer_r.encode_plus , __snake_case , max_length=__snake_case , padding='''max_length''' ) # Pair input self.assertRaises( __snake_case , tokenizer_r.batch_encode_plus , __snake_case , max_length=__snake_case , padding='''max_length''' , ) def a_ ( self ): pass @require_ftfy @require_spacy @require_tokenizers class A__ ( a__ ): """simple docstring""" pass
127
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: __UpperCamelCase : Dict = False __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : int = 'ybelkada/fonts' def A ( ): if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( f"""You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use """ '''Pix2StructImageProcessor. Please upgrade torch.''' ) def A ( _lowercase , _lowercase , _lowercase ): requires_backends(__A , ['''torch'''] ) _check_torch_version() SCREAMING_SNAKE_CASE : int = image_tensor.unsqueeze(0 ) SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.unfold(__A , (patch_height, patch_width) , stride=(patch_height, patch_width) ) SCREAMING_SNAKE_CASE : Union[str, Any] = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , __A , __A , -1 ) SCREAMING_SNAKE_CASE : Optional[int] = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def A ( _lowercase , _lowercase = 36 , _lowercase = "black" , _lowercase = "white" , _lowercase = 5 , _lowercase = 5 , _lowercase = 5 , _lowercase = 5 , _lowercase = None , _lowercase = None , ): requires_backends(__A , '''vision''' ) # Add new lines so that each line is no more than 80 characters. SCREAMING_SNAKE_CASE : str = textwrap.TextWrapper(width=80 ) SCREAMING_SNAKE_CASE : int = wrapper.wrap(text=__A ) SCREAMING_SNAKE_CASE : List[Any] = '''\n'''.join(__A ) if font_bytes is not None and font_path is None: SCREAMING_SNAKE_CASE : Tuple = io.BytesIO(__A ) elif font_path is not None: SCREAMING_SNAKE_CASE : Optional[int] = font_path else: SCREAMING_SNAKE_CASE : Union[str, Any] = hf_hub_download(__A , '''Arial.TTF''' ) SCREAMING_SNAKE_CASE : Dict = ImageFont.truetype(__A , encoding='''UTF-8''' , size=__A ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. SCREAMING_SNAKE_CASE : Any = ImageDraw.Draw(Image.new('''RGB''' , (1, 1) , __A ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = temp_draw.textbbox((0, 0) , __A , __A ) # Create the actual image with a bit of padding around the text. SCREAMING_SNAKE_CASE : Union[str, Any] = text_width + left_padding + right_padding SCREAMING_SNAKE_CASE : Any = text_height + top_padding + bottom_padding SCREAMING_SNAKE_CASE : Union[str, Any] = Image.new('''RGB''' , (image_width, image_height) , __A ) SCREAMING_SNAKE_CASE : List[Any] = ImageDraw.Draw(__A ) draw.text(xy=(left_padding, top_padding) , text=__A , fill=__A , font=__A ) return image def A ( _lowercase , _lowercase , **_lowercase ): requires_backends(__A , '''vision''' ) # Convert to PIL image if necessary SCREAMING_SNAKE_CASE : List[str] = to_pil_image(__A ) SCREAMING_SNAKE_CASE : Any = render_text(__A , **__A ) SCREAMING_SNAKE_CASE : int = max(header_image.width , image.width ) SCREAMING_SNAKE_CASE : Tuple = int(image.height * (new_width / image.width) ) SCREAMING_SNAKE_CASE : Dict = int(header_image.height * (new_width / header_image.width) ) SCREAMING_SNAKE_CASE : Any = Image.new('''RGB''' , (new_width, new_height + new_header_height) , '''white''' ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary SCREAMING_SNAKE_CASE : List[Any] = to_numpy_array(__A ) if infer_channel_dimension_format(__A ) == ChannelDimension.LAST: SCREAMING_SNAKE_CASE : List[Any] = to_channel_dimension_format(__A , ChannelDimension.LAST ) return new_image class lowercase__ ( a__): UpperCamelCase_ = ["""flattened_patches"""] def __init__( self : Tuple , UpperCamelCase__ : Optional[int] = True , UpperCamelCase__ : Dict = True , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[Any] = 2048 , UpperCamelCase__ : Tuple = False , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} SCREAMING_SNAKE_CASE : List[str] = do_normalize SCREAMING_SNAKE_CASE : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE : Optional[Any] = max_patches SCREAMING_SNAKE_CASE : str = is_vqa def __A ( self : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , **UpperCamelCase__ : int ): '''simple docstring''' requires_backends(self.extract_flattened_patches , '''torch''' ) _check_torch_version() # convert to torch SCREAMING_SNAKE_CASE : Tuple = to_channel_dimension_format(UpperCamelCase__ , ChannelDimension.FIRST ) SCREAMING_SNAKE_CASE : List[str] = torch.from_numpy(UpperCamelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = patch_size['''height'''], patch_size['''width'''] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = get_image_size(UpperCamelCase__ ) # maximize scale s.t. SCREAMING_SNAKE_CASE : List[Any] = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) SCREAMING_SNAKE_CASE : Tuple = max(min(math.floor(scale * image_height / patch_height ) , UpperCamelCase__ ) , 1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = max(min(math.floor(scale * image_width / patch_width ) , UpperCamelCase__ ) , 1 ) SCREAMING_SNAKE_CASE : List[Any] = max(num_feasible_rows * patch_height , 1 ) SCREAMING_SNAKE_CASE : List[Any] = max(num_feasible_cols * patch_width , 1 ) SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode='''bilinear''' , align_corners=UpperCamelCase__ , antialias=UpperCamelCase__ , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE : List[Any] = torch_extract_patches(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = patches.shape SCREAMING_SNAKE_CASE : Dict = patches_shape[1] SCREAMING_SNAKE_CASE : List[str] = patches_shape[2] SCREAMING_SNAKE_CASE : Tuple = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE : Tuple = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] SCREAMING_SNAKE_CASE : Dict = torch.arange(UpperCamelCase__ ).reshape([rows, 1] ).repeat(1 , UpperCamelCase__ ).reshape([rows * columns, 1] ) SCREAMING_SNAKE_CASE : int = torch.arange(UpperCamelCase__ ).reshape([1, columns] ).repeat(UpperCamelCase__ , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] SCREAMING_SNAKE_CASE : Optional[int] = row_ids.to(torch.floataa ) SCREAMING_SNAKE_CASE : Optional[int] = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE : List[Any] = torch.nn.functional.pad(UpperCamelCase__ , [0, 0, 0, max_patches - (rows * columns)] ).float() SCREAMING_SNAKE_CASE : List[str] = to_numpy_array(UpperCamelCase__ ) return result def __A ( self : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict = None , **UpperCamelCase__ : str ): '''simple docstring''' if image.dtype == np.uinta: SCREAMING_SNAKE_CASE : Any = image.astype(np.floataa ) # take mean across the whole `image` SCREAMING_SNAKE_CASE : Any = np.mean(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = np.std(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = max(UpperCamelCase__ , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : int , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] = None , UpperCamelCase__ : Dict = None , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[Any] = None , UpperCamelCase__ : List[Any] = None , UpperCamelCase__ : Union[str, Any] = None , UpperCamelCase__ : List[str] = ChannelDimension.FIRST , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb SCREAMING_SNAKE_CASE : Dict = patch_size if patch_size is not None else self.patch_size SCREAMING_SNAKE_CASE : Any = max_patches if max_patches is not None else self.max_patches SCREAMING_SNAKE_CASE : Tuple = self.is_vqa if kwargs.get('''data_format''' , UpperCamelCase__ ) is not None: raise ValueError('''data_format is not an accepted input as the outputs are ''' ) SCREAMING_SNAKE_CASE : int = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: SCREAMING_SNAKE_CASE : Any = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Dict = [to_numpy_array(UpperCamelCase__ ) for image in images] if is_vqa: if header_text is None: raise ValueError('''A header text must be provided for VQA models.''' ) SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop('''font_bytes''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = kwargs.pop('''font_path''' , UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = [header_text] * len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = [ render_header(UpperCamelCase__ , header_text[i] , font_bytes=UpperCamelCase__ , font_path=UpperCamelCase__ ) for i, image in enumerate(UpperCamelCase__ ) ] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=UpperCamelCase__ ) for image in images] # convert to torch tensor and permute SCREAMING_SNAKE_CASE : str = [ self.extract_flattened_patches(image=UpperCamelCase__ , max_patches=UpperCamelCase__ , patch_size=UpperCamelCase__ ) for image in images ] # create attention mask in numpy SCREAMING_SNAKE_CASE : Optional[Any] = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] SCREAMING_SNAKE_CASE : Tuple = BatchFeature( data={'''flattened_patches''': images, '''attention_mask''': attention_masks} , tensor_type=UpperCamelCase__ ) return encoded_outputs
182
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json', 'allenai/longformer-large-4096': 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json', 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE_ ( a__ ): __lowerCAmelCase = """longformer""" def __init__( self : Optional[Any] , lowerCamelCase_ : int = 512 , lowerCamelCase_ : Optional[int] = 2 , lowerCamelCase_ : Union[str, Any] = 1 , lowerCamelCase_ : Dict = 0 , lowerCamelCase_ : int = 2 , lowerCamelCase_ : str = 3_0522 , lowerCamelCase_ : Optional[Any] = 768 , lowerCamelCase_ : Optional[int] = 12 , lowerCamelCase_ : List[str] = 12 , lowerCamelCase_ : Optional[Any] = 3072 , lowerCamelCase_ : Optional[Any] = "gelu" , lowerCamelCase_ : str = 0.1 , lowerCamelCase_ : Union[str, Any] = 0.1 , lowerCamelCase_ : Dict = 512 , lowerCamelCase_ : Dict = 2 , lowerCamelCase_ : Optional[Any] = 0.0_2 , lowerCamelCase_ : List[Any] = 1E-12 , lowerCamelCase_ : str = False , **lowerCamelCase_ : List[str] , ): """simple docstring""" super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ ) UpperCamelCase = attention_window UpperCamelCase = sep_token_id UpperCamelCase = bos_token_id UpperCamelCase = eos_token_id UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = onnx_export class SCREAMING_SNAKE_CASE_ ( a__ ): def __init__( self : List[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] = "default" , lowerCamelCase_ : int = None ): """simple docstring""" super().__init__(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = True @property def lowerCamelCase_ ( self : Dict ): """simple docstring""" if self.task == "multiple-choice": UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""global_attention_mask""", dynamic_axis), ] ) @property def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = super().outputs if self.task == "default": UpperCamelCase = {0: """batch"""} return outputs @property def lowerCamelCase_ ( self : List[str] ): """simple docstring""" return 1E-4 @property def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" return max(super().default_onnx_opset , 14 ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Dict = -1 , lowerCamelCase_ : Optional[int] = -1 , lowerCamelCase_ : List[str] = False , lowerCamelCase_ : Union[str, Any] = None , ): """simple docstring""" UpperCamelCase = super().generate_dummy_inputs( preprocessor=lowerCamelCase_ , batch_size=lowerCamelCase_ , seq_length=lowerCamelCase_ , is_pair=lowerCamelCase_ , framework=lowerCamelCase_ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly UpperCamelCase = torch.zeros_like(inputs["""input_ids"""] ) # make every second token global UpperCamelCase = 1 return inputs
343
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ = logging.get_logger(__name__) A_ = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class _snake_case ( a__ , a__ ): _A : Union[str, Any] = '''convnextv2''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : int=3 ,SCREAMING_SNAKE_CASE__ : str=4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=4 ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None ,SCREAMING_SNAKE_CASE__ : Any="gelu" ,SCREAMING_SNAKE_CASE__ : List[str]=0.02 ,SCREAMING_SNAKE_CASE__ : Any=1e-12 ,SCREAMING_SNAKE_CASE__ : str=0.0 ,SCREAMING_SNAKE_CASE__ : str=224 ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : int=None ,**SCREAMING_SNAKE_CASE__ : Tuple ,): super().__init__(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = num_channels SCREAMING_SNAKE_CASE:int = patch_size SCREAMING_SNAKE_CASE:Union[str, Any] = num_stages SCREAMING_SNAKE_CASE:str = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes SCREAMING_SNAKE_CASE:Any = [3, 3, 9, 3] if depths is None else depths SCREAMING_SNAKE_CASE:List[Any] = hidden_act SCREAMING_SNAKE_CASE:List[str] = initializer_range SCREAMING_SNAKE_CASE:Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE:str = drop_path_rate SCREAMING_SNAKE_CASE:Tuple = image_size SCREAMING_SNAKE_CASE:Any = ["stem"] + [F'''stage{idx}''' for idx in range(1 ,len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:Optional[int] = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE__ ,out_indices=SCREAMING_SNAKE_CASE__ ,stage_names=self.stage_names )
139
'''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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = 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: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
def A ( a_ ) -> "list[int]": if upper_limit < 0: raise ValueError('Limit for the Catalan sequence must be ≥ 0' ) __UpperCamelCase : Union[str, Any] =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __UpperCamelCase : Optional[int] =1 if upper_limit > 0: __UpperCamelCase : Dict =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 ,upper_limit + 1 ): for j in range(__A ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: A_ :Tuple = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
71
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = 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 __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule snake_case_ : Dict = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys snake_case_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
83
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
def snake_case ( snake_case__ :List[Any]) -> bool: return sum(i for i in range(1 , number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": print('Program to check whether a number is a Perfect number or not...') _SCREAMING_SNAKE_CASE = int(input('Enter number: ').strip()) print(F'''{number} is {"" if perfect(number) else "not "}a Perfect Number.''')
180
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
'''simple docstring''' def lowerCamelCase ( UpperCAmelCase__ : Optional[int] ) -> str: if number > 0: raise ValueError("""input must be a negative integer""" ) lowercase_ : Dict = len(bin(__A )[3:] ) lowercase_ : Union[str, Any] = bin(abs(__A ) - (1 << binary_number_length) )[3:] lowercase_ : Optional[int] = ( ( """1""" + """0""" * (binary_number_length - len(__A )) + twos_complement_number ) if number < 0 else """0""" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
239
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
'''simple docstring''' from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class lowerCamelCase_ (a__ ): '''simple docstring''' def __init__( self : Optional[int] , A : str , A : int ): super().__init__() self.register_modules(unet=A , scheduler=A ) @torch.no_grad() def __call__( self : Dict , A : Dict = 1 , A : Optional[int] = None , A : List[Any] = 50 , A : Union[str, Any] = "pil" , A : Tuple = True , **A : Dict , ): _UpperCAmelCase : Optional[int] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=A , ) _UpperCAmelCase : Union[str, Any] = image.to(self.device ) # set step values self.scheduler.set_timesteps(A ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _UpperCAmelCase : 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 _UpperCAmelCase : List[Any] = self.scheduler.step(A , A , A ).prev_sample _UpperCAmelCase : Tuple = (image / 2 + 0.5).clamp(0 , 1 ) _UpperCAmelCase : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _UpperCAmelCase : str = self.numpy_to_pil(A ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=A ), "This is a local test"
31
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets _UpperCAmelCase : List[Any] = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' _UpperCAmelCase : Tuple = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' _UpperCAmelCase : Union[str, Any] = R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase ( datasets.Metric ): def A_ ( self : Union[str, Any] ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/hendrycks/math' , codebase_urls=['https://github.com/hendrycks/math'] , ) def A_ ( self : int , UpperCAmelCase : Dict , UpperCAmelCase : Tuple ) -> List[str]: lowerCamelCase__ : List[Any] = 0.0 for i, j in zip(UpperCAmelCase , UpperCAmelCase ): n_correct += 1.0 if math_equivalence.is_equiv(UpperCAmelCase , UpperCAmelCase ) else 0.0 lowerCamelCase__ : List[str] = n_correct / len(UpperCAmelCase ) return { "accuracy": accuracy, }
50
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class __snake_case ( a__ ): a__ = """lilt""" def __init__( self , lowercase=3_05_22 , lowercase=7_68 , lowercase=12 , lowercase=12 , lowercase=30_72 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=5_12 , lowercase=2 , lowercase=0.02 , lowercase=1e-12 , lowercase=0 , lowercase="absolute" , lowercase=None , lowercase=4 , lowercase=10_24 , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowercase , **lowercase) a__: Union[str, Any] = vocab_size a__: Any = hidden_size a__: Any = num_hidden_layers a__: Union[str, Any] = num_attention_heads a__: int = hidden_act a__: Tuple = intermediate_size a__: Union[str, Any] = hidden_dropout_prob a__: Optional[Any] = attention_probs_dropout_prob a__: Any = max_position_embeddings a__: List[Any] = type_vocab_size a__: Any = initializer_range a__: Tuple = layer_norm_eps a__: Tuple = position_embedding_type a__: List[Any] = classifier_dropout a__: Union[str, Any] = channel_shrink_ratio a__: Dict = max_ad_position_embeddings
290
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
import argparse import logging import pickle from collections import Counter logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) _SCREAMING_SNAKE_CASE : Dict = logging.getLogger(__name__) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser( description="Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)" ) parser.add_argument( "--data_file", type=str, default="data/dump.bert-base-uncased.pickle", help="The binarized dataset." ) parser.add_argument( "--token_counts_dump", type=str, default="data/token_counts.bert-base-uncased.pickle", help="The dump file." ) parser.add_argument("--vocab_size", default=3_05_22, type=int) _SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, "rb") as fp: _SCREAMING_SNAKE_CASE : Union[str, Any] = pickle.load(fp) logger.info("Counting occurrences for MLM.") _SCREAMING_SNAKE_CASE : List[str] = Counter() for tk_ids in data: counter.update(tk_ids) _SCREAMING_SNAKE_CASE : str = [0] * args.vocab_size for k, v in counter.items(): _SCREAMING_SNAKE_CASE : Any = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, "wb") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
127
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class lowercase__ ( unittest.TestCase): UpperCamelCase_ = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCamelCase_ = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def __A ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TextaTextGenerationPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) return generator, ["Something to write", "Something else"] def __A ( self : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = generator('''Something there''' ) self.assertEqual(UpperCamelCase__ , [{'''generated_text''': ANY(UpperCamelCase__ )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['''generated_text'''].startswith('''Something there''' ) ) SCREAMING_SNAKE_CASE : str = generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ [{'''generated_text''': ANY(UpperCamelCase__ )}, {'''generated_text''': ANY(UpperCamelCase__ )}], [{'''generated_text''': ANY(UpperCamelCase__ )}, {'''generated_text''': ANY(UpperCamelCase__ )}], ] , ) SCREAMING_SNAKE_CASE : Optional[int] = generator( ['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ [{'''generated_text''': ANY(UpperCamelCase__ )}, {'''generated_text''': ANY(UpperCamelCase__ )}], [{'''generated_text''': ANY(UpperCamelCase__ )}, {'''generated_text''': ANY(UpperCamelCase__ )}], ] , ) with self.assertRaises(UpperCamelCase__ ): generator(4 ) @require_torch def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''pt''' ) # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE : Dict = generator('''Something there''' , do_sample=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , [{'''generated_text''': ''''''}] ) SCREAMING_SNAKE_CASE : Tuple = 3 SCREAMING_SNAKE_CASE : Union[str, Any] = generator( '''Something there''' , num_return_sequences=UpperCamelCase__ , num_beams=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': ''''''}, ] self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = generator('''This is a test''' , do_sample=UpperCamelCase__ , num_return_sequences=2 , return_tensors=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ {'''generated_token_ids''': ANY(torch.Tensor )}, {'''generated_token_ids''': ANY(torch.Tensor )}, ] , ) SCREAMING_SNAKE_CASE : int = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE : Tuple = '''<pad>''' SCREAMING_SNAKE_CASE : Optional[Any] = generator( ['''This is a test''', '''This is a second test'''] , do_sample=UpperCamelCase__ , num_return_sequences=2 , batch_size=2 , return_tensors=UpperCamelCase__ , ) self.assertEqual( UpperCamelCase__ , [ [ {'''generated_token_ids''': ANY(torch.Tensor )}, {'''generated_token_ids''': ANY(torch.Tensor )}, ], [ {'''generated_token_ids''': ANY(torch.Tensor )}, {'''generated_token_ids''': ANY(torch.Tensor )}, ], ] , ) @require_tf def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''tf''' ) # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE : Optional[Any] = generator('''Something there''' , do_sample=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , [{'''generated_text''': ''''''}] )
182
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
def lowercase( UpperCamelCase_ ) -> list[int]: '''simple docstring''' if num <= 0: raise ValueError("""Input must be a positive integer""" ) UpperCamelCase = [True] * (num + 1) UpperCamelCase = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , __A ): UpperCamelCase = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() _SCREAMING_SNAKE_CASE = int(input("""Enter a positive integer: """).strip()) print(prime_sieve_eratosthenes(user_num))
343
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): 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 , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [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 __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class _snake_case : def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[Any]=13 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : List[Any]=99 ,SCREAMING_SNAKE_CASE__ : Any=32 ,SCREAMING_SNAKE_CASE__ : Optional[int]=2 ,SCREAMING_SNAKE_CASE__ : int=4 ,SCREAMING_SNAKE_CASE__ : Tuple=37 ,SCREAMING_SNAKE_CASE__ : str="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : int=512 ,SCREAMING_SNAKE_CASE__ : List[str]=16 ,SCREAMING_SNAKE_CASE__ : str=2 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.02 ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="None" ,SCREAMING_SNAKE_CASE__ : str=3 ,SCREAMING_SNAKE_CASE__ : Optional[int]=4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,): SCREAMING_SNAKE_CASE:Optional[Any] = parent SCREAMING_SNAKE_CASE:Optional[int] = batch_size SCREAMING_SNAKE_CASE:int = seq_length SCREAMING_SNAKE_CASE:str = is_training SCREAMING_SNAKE_CASE:List[str] = use_input_mask SCREAMING_SNAKE_CASE:Tuple = use_token_type_ids SCREAMING_SNAKE_CASE:Union[str, Any] = use_labels SCREAMING_SNAKE_CASE:Any = vocab_size SCREAMING_SNAKE_CASE:Any = hidden_size SCREAMING_SNAKE_CASE:Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE:Tuple = num_attention_heads SCREAMING_SNAKE_CASE:Any = intermediate_size SCREAMING_SNAKE_CASE:Dict = hidden_act SCREAMING_SNAKE_CASE:Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE:Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE:Dict = max_position_embeddings SCREAMING_SNAKE_CASE:List[Any] = type_vocab_size SCREAMING_SNAKE_CASE:int = type_sequence_label_size SCREAMING_SNAKE_CASE:List[Any] = initializer_range SCREAMING_SNAKE_CASE:Dict = num_labels SCREAMING_SNAKE_CASE:str = num_choices SCREAMING_SNAKE_CASE:Dict = relative_attention SCREAMING_SNAKE_CASE:Union[str, Any] = position_biased_input SCREAMING_SNAKE_CASE:Union[str, Any] = pos_att_type SCREAMING_SNAKE_CASE:Dict = scope def __UpperCamelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE:Optional[int] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE:Optional[int] = None if self.use_input_mask: SCREAMING_SNAKE_CASE:Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE:Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE:Dict = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) SCREAMING_SNAKE_CASE:Dict = None SCREAMING_SNAKE_CASE:List[Any] = None SCREAMING_SNAKE_CASE:Any = None if self.use_labels: SCREAMING_SNAKE_CASE:Optional[Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE:int = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE:Tuple = DebertaVaConfig( 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 ,relative_attention=self.relative_attention ,position_biased_input=self.position_biased_input ,initializer_range=self.initializer_range ,return_dict=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ): SCREAMING_SNAKE_CASE:Optional[Any] = TFDebertaVaModel(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[str] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE:List[Any] = [input_ids, input_mask] SCREAMING_SNAKE_CASE:Optional[int] = model(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:int = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Tuple ): SCREAMING_SNAKE_CASE:Dict = TFDebertaVaForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[str] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE:List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[Any] ): SCREAMING_SNAKE_CASE:Any = self.num_labels SCREAMING_SNAKE_CASE:int = TFDebertaVaForSequenceClassification(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Optional[int] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE:List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __UpperCamelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ): SCREAMING_SNAKE_CASE:List[str] = self.num_labels SCREAMING_SNAKE_CASE:Optional[int] = TFDebertaVaForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE:List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ): SCREAMING_SNAKE_CASE:Optional[int] = TFDebertaVaForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[str] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE:List[Any] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def __UpperCamelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE:Optional[Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ):List[Any] = config_and_inputs SCREAMING_SNAKE_CASE:List[str] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _snake_case ( a__ , a__ , unittest.TestCase ): _A : Optional[Any] = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) _A : Tuple = ( { '''feature-extraction''': TFDebertaVaModel, '''fill-mask''': TFDebertaVaForMaskedLM, '''question-answering''': TFDebertaVaForQuestionAnswering, '''text-classification''': TFDebertaVaForSequenceClassification, '''token-classification''': TFDebertaVaForTokenClassification, '''zero-shot''': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) _A : int = False _A : Dict = False def __UpperCamelCase ( self : str ): SCREAMING_SNAKE_CASE:List[str] = TFDebertaVaModelTester(self ) SCREAMING_SNAKE_CASE:Optional[Any] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,hidden_size=37 ) def __UpperCamelCase ( self : Union[str, Any] ): self.config_tester.run_common_tests() def __UpperCamelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE:Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : Dict ): SCREAMING_SNAKE_CASE:List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : Any ): SCREAMING_SNAKE_CASE:Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : List[str] ): SCREAMING_SNAKE_CASE:List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE:Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def __UpperCamelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE:List[Any] = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_tf class _snake_case ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def __UpperCamelCase ( self : Union[str, Any] ): pass @slow def __UpperCamelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE:str = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) SCREAMING_SNAKE_CASE:int = tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) SCREAMING_SNAKE_CASE:Dict = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) SCREAMING_SNAKE_CASE:Any = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ )[0] SCREAMING_SNAKE_CASE:int = tf.constant( [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1e-4 )
139
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): 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 token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
import pytest A_ :str = '__dummy_dataset1__' A_ :Union[str, Any] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def A ( ) -> Tuple: return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def A ( ) -> str: return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def A ( a_ ,a_ ,a_ ) -> Any: __UpperCamelCase : Optional[Any] =dataset_loading_script_name __UpperCamelCase : str =tmp_path / 'datasets' / script_name script_dir.mkdir(parents=__A ) __UpperCamelCase : Union[str, Any] =script_dir / F'{script_name}.py' with open(__A ,'w' ) as f: f.write(__A ) return str(__A )
71
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase__ ( unittest.TestCase ): def __init__( self : Optional[int] ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[Any]=3 ,lowerCamelCase__ : List[Any]=32 ,lowerCamelCase__ : int=3 ,lowerCamelCase__ : Dict=10 ,lowerCamelCase__ : int=[10, 20, 30, 40] ,lowerCamelCase__ : Union[str, Any]=[1, 1, 2, 1] ,lowerCamelCase__ : int=True ,lowerCamelCase__ : Any=True ,lowerCamelCase__ : Dict="relu" ,lowerCamelCase__ : Optional[Any]=3 ,lowerCamelCase__ : Dict=None ,): '''simple docstring''' _UpperCamelCase : Optional[int] = parent _UpperCamelCase : Any = batch_size _UpperCamelCase : Union[str, Any] = image_size _UpperCamelCase : Any = num_channels _UpperCamelCase : Optional[Any] = embeddings_size _UpperCamelCase : Optional[int] = hidden_sizes _UpperCamelCase : Union[str, Any] = depths _UpperCamelCase : Optional[Any] = is_training _UpperCamelCase : Union[str, Any] = use_labels _UpperCamelCase : int = hidden_act _UpperCamelCase : Tuple = num_labels _UpperCamelCase : Union[str, Any] = scope _UpperCamelCase : Union[str, Any] = len(lowerCamelCase__ ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCamelCase : Optional[Any] = self.get_config() return config, pixel_values def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' return RegNetConfig( num_channels=self.num_channels ,embeddings_size=self.embeddings_size ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,hidden_act=self.hidden_act ,num_labels=self.num_labels ,image_size=self.image_size ,) def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ): '''simple docstring''' _UpperCamelCase : Optional[int] = FlaxRegNetModel(config=lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = model(lowerCamelCase__ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : List[str] = self.num_labels _UpperCamelCase : str = FlaxRegNetForImageClassification(config=lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = model(lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' _UpperCamelCase : Any = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase : List[Any] = config_and_inputs _UpperCamelCase : int = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class lowercase__ ( a__ , unittest.TestCase ): lowercase__ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () lowercase__ = False lowercase__ = False lowercase__ = False def UpperCamelCase_ ( self : Dict ): '''simple docstring''' _UpperCamelCase : Optional[Any] = FlaxRegNetModelTester(self ) _UpperCamelCase : Tuple = ConfigTester(self ,config_class=lowerCamelCase__ ,has_text_modality=lowerCamelCase__ ) def UpperCamelCase_ ( self : Any ): '''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 UpperCamelCase_ ( self : Any ): '''simple docstring''' return def UpperCamelCase_ ( self : int ): '''simple docstring''' _UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ ) @unittest.skip(reason='RegNet does not use inputs_embeds' ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @unittest.skip(reason='RegNet does not support input and output embeddings' ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' pass def UpperCamelCase_ ( self : str ): '''simple docstring''' _UpperCamelCase , _UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : int = model_class(lowerCamelCase__ ) _UpperCamelCase : Optional[int] = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCamelCase : int = [*signature.parameters.keys()] _UpperCamelCase : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,lowerCamelCase__ ) def UpperCamelCase_ ( self : str ): '''simple docstring''' def check_hidden_states_output(lowerCamelCase__ : Tuple ,lowerCamelCase__ : str ,lowerCamelCase__ : int ): _UpperCamelCase : Tuple = model_class(lowerCamelCase__ ) _UpperCamelCase : str = model(**self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ) ) _UpperCamelCase : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _UpperCamelCase : Optional[int] = self.model_tester.num_stages self.assertEqual(len(lowerCamelCase__ ) ,expected_num_stages + 1 ) _UpperCamelCase , _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : Optional[Any] = True check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCamelCase : Any = True check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' _UpperCamelCase , _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _UpperCamelCase : int = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ) _UpperCamelCase : List[Any] = model_class(lowerCamelCase__ ) @jax.jit def model_jitted(lowerCamelCase__ : List[str] ,**lowerCamelCase__ : Tuple ): return model(pixel_values=lowerCamelCase__ ,**lowerCamelCase__ ) with self.subTest('JIT Enabled' ): _UpperCamelCase : List[str] = model_jitted(**lowerCamelCase__ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): _UpperCamelCase : Union[str, Any] = model_jitted(**lowerCamelCase__ ).to_tuple() self.assertEqual(len(lowerCamelCase__ ) ,len(lowerCamelCase__ ) ) for jitted_output, output in zip(lowerCamelCase__ ,lowerCamelCase__ ): self.assertEqual(jitted_output.shape ,output.shape ) def A__ ( ): _UpperCamelCase : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_flax class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' return AutoImageProcessor.from_pretrained('facebook/regnet-y-040' ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : int ): '''simple docstring''' _UpperCamelCase : Tuple = FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040' ) _UpperCamelCase : Tuple = self.default_image_processor _UpperCamelCase : int = prepare_img() _UpperCamelCase : str = image_processor(images=lowerCamelCase__ ,return_tensors='np' ) _UpperCamelCase : List[Any] = model(**lowerCamelCase__ ) # verify the logits _UpperCamelCase : List[str] = (1, 1000) self.assertEqual(outputs.logits.shape ,lowerCamelCase__ ) _UpperCamelCase : Dict = jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] ,lowerCamelCase__ ,atol=1E-4 ) )
83
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class a ( a__ ): """simple docstring""" lowerCamelCase :Optional[int] = '''deta''' lowerCamelCase :List[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , lowerCAmelCase_=None , lowerCAmelCase_=9_00 , lowerCAmelCase_=20_48 , lowerCAmelCase_=6 , lowerCAmelCase_=20_48 , lowerCAmelCase_=8 , lowerCAmelCase_=6 , lowerCAmelCase_=10_24 , lowerCAmelCase_=8 , lowerCAmelCase_=0.0 , lowerCAmelCase_=True , lowerCAmelCase_="relu" , lowerCAmelCase_=2_56 , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.02 , lowerCAmelCase_=1.0 , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_="sine" , lowerCAmelCase_=5 , lowerCAmelCase_=4 , lowerCAmelCase_=4 , lowerCAmelCase_=True , lowerCAmelCase_=3_00 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=1 , lowerCAmelCase_=5 , lowerCAmelCase_=2 , lowerCAmelCase_=1 , lowerCAmelCase_=1 , lowerCAmelCase_=5 , lowerCAmelCase_=2 , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.25 , **lowerCAmelCase_ , ) -> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) _A = CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _A = backbone_config.pop("""model_type""" ) _A = CONFIG_MAPPING[backbone_model_type] _A = config_class.from_dict(lowerCAmelCase_ ) _A = backbone_config _A = num_queries _A = max_position_embeddings _A = d_model _A = encoder_ffn_dim _A = encoder_layers _A = encoder_attention_heads _A = decoder_ffn_dim _A = decoder_layers _A = decoder_attention_heads _A = dropout _A = attention_dropout _A = activation_dropout _A = activation_function _A = init_std _A = init_xavier_std _A = encoder_layerdrop _A = auxiliary_loss _A = position_embedding_type # deformable attributes _A = num_feature_levels _A = encoder_n_points _A = decoder_n_points _A = two_stage _A = two_stage_num_proposals _A = with_box_refine _A = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher _A = class_cost _A = bbox_cost _A = giou_cost # Loss coefficients _A = mask_loss_coefficient _A = dice_loss_coefficient _A = bbox_loss_coefficient _A = giou_loss_coefficient _A = eos_coefficient _A = focal_alpha super().__init__(is_encoder_decoder=lowerCAmelCase_ , **lowerCAmelCase_ ) @property def UpperCAmelCase ( self ) -> List[str]: return self.encoder_attention_heads @property def UpperCAmelCase ( self ) -> List[Any]: return self.d_model def UpperCAmelCase ( self ) -> str: _A = copy.deepcopy(self.__dict__ ) _A = self.backbone_config.to_dict() _A = self.__class__.model_type return output
180
'''simple docstring''' # Copyright 2021 The HuggingFace 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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
'''simple docstring''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase ( ) -> Optional[Any]: lowercase_ : int = """https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png""" lowercase_ : str = Image.open(requests.get(__A , stream=__A ).raw ).convert("""RGB""" ) return image def lowerCamelCase ( UpperCAmelCase__ : str ) -> Optional[Any]: lowercase_ : List[str] = [] # fmt: off # vision encoder rename_keys.append(("""visual_encoder.cls_token""", """vision_model.embeddings.class_embedding""") ) rename_keys.append(("""visual_encoder.pos_embed""", """vision_model.embeddings.position_embedding""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.weight""", """vision_model.embeddings.patch_embedding.weight""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.bias""", """vision_model.embeddings.patch_embedding.bias""") ) rename_keys.append(("""ln_vision.weight""", """vision_model.post_layernorm.weight""") ) rename_keys.append(("""ln_vision.bias""", """vision_model.post_layernorm.bias""") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.weight""", """qformer.layernorm.weight""") ) rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.bias""", """qformer.layernorm.bias""") ) # fmt: on return rename_keys def lowerCamelCase ( UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] ) -> List[Any]: lowercase_ : int = dct.pop(__A ) lowercase_ : List[Any] = val def lowerCamelCase ( UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Optional[Any]: for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases lowercase_ : List[str] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) lowercase_ : Dict = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict lowercase_ : Union[str, Any] = torch.cat((q_bias, torch.zeros_like(__A , requires_grad=__A ), v_bias) ) lowercase_ : Any = qkv_bias def lowerCamelCase ( UpperCAmelCase__ : str , UpperCAmelCase__ : str ) -> Any: lowercase_ : Any = 364 if """coco""" in model_name else 224 lowercase_ : List[Any] = BlipaVisionConfig(image_size=__A ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: lowercase_ : Optional[int] = OPTConfig.from_pretrained("""facebook/opt-2.7b""" , eos_token_id=__A ).to_dict() elif "opt-6.7b" in model_name: lowercase_ : Union[str, Any] = OPTConfig.from_pretrained("""facebook/opt-6.7b""" , eos_token_id=__A ).to_dict() elif "t5-xl" in model_name: lowercase_ : Union[str, Any] = TaConfig.from_pretrained("""google/flan-t5-xl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: lowercase_ : List[Any] = TaConfig.from_pretrained("""google/flan-t5-xxl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() lowercase_ : List[str] = BlipaConfig(vision_config=__A , text_config=__A ) return config, image_size @torch.no_grad() def lowerCamelCase ( UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=False ) -> Any: lowercase_ : Optional[Any] = ( AutoTokenizer.from_pretrained("""facebook/opt-2.7b""" ) if """opt""" in model_name else AutoTokenizer.from_pretrained("""google/flan-t5-xl""" ) ) lowercase_ : Optional[int] = tokenizer("""\n""" , add_special_tokens=__A ).input_ids[0] lowercase_ , lowercase_ : Dict = get_blipa_config(__A , eos_token_id=__A ) lowercase_ : Optional[int] = BlipaForConditionalGeneration(__A ).eval() lowercase_ : Optional[int] = { """blip2-opt-2.7b""": ("""blip2_opt""", """pretrain_opt2.7b"""), """blip2-opt-6.7b""": ("""blip2_opt""", """pretrain_opt6.7b"""), """blip2-opt-2.7b-coco""": ("""blip2_opt""", """caption_coco_opt2.7b"""), """blip2-opt-6.7b-coco""": ("""blip2_opt""", """caption_coco_opt6.7b"""), """blip2-flan-t5-xl""": ("""blip2_t5""", """pretrain_flant5xl"""), """blip2-flan-t5-xl-coco""": ("""blip2_t5""", """caption_coco_flant5xl"""), """blip2-flan-t5-xxl""": ("""blip2_t5""", """pretrain_flant5xxl"""), } lowercase_ , lowercase_ : str = model_name_to_original[model_name] # load original model print("""Loading original model...""" ) lowercase_ : Any = """cuda""" if torch.cuda.is_available() else """cpu""" lowercase_ , lowercase_ , lowercase_ : Optional[int] = load_model_and_preprocess( name=__A , model_type=__A , is_eval=__A , device=__A ) original_model.eval() print("""Done!""" ) # update state dict keys lowercase_ : Union[str, Any] = original_model.state_dict() lowercase_ : Union[str, Any] = create_rename_keys(__A ) for src, dest in rename_keys: rename_key(__A , __A , __A ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): lowercase_ : int = state_dict.pop(__A ) if key.startswith("""Qformer.bert""" ): lowercase_ : int = key.replace("""Qformer.bert""" , """qformer""" ) if "attention.self" in key: lowercase_ : Optional[int] = key.replace("""self""" , """attention""" ) if "opt_proj" in key: lowercase_ : Union[str, Any] = key.replace("""opt_proj""" , """language_projection""" ) if "t5_proj" in key: lowercase_ : str = key.replace("""t5_proj""" , """language_projection""" ) if key.startswith("""opt""" ): lowercase_ : Tuple = key.replace("""opt""" , """language""" ) if key.startswith("""t5""" ): lowercase_ : int = key.replace("""t5""" , """language""" ) lowercase_ : Tuple = val # read in qv biases read_in_q_v_bias(__A , __A ) lowercase_ , lowercase_ : List[Any] = hf_model.load_state_dict(__A , strict=__A ) assert len(__A ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] lowercase_ : Optional[Any] = load_demo_image() lowercase_ : Optional[Any] = vis_processors["""eval"""](__A ).unsqueeze(0 ).to(__A ) lowercase_ : Union[str, Any] = tokenizer(["""\n"""] , return_tensors="""pt""" ).input_ids.to(__A ) # create processor lowercase_ : Tuple = BlipImageProcessor( size={"""height""": image_size, """width""": image_size} , image_mean=__A , image_std=__A ) lowercase_ : Union[str, Any] = BlipaProcessor(image_processor=__A , tokenizer=__A ) lowercase_ : List[str] = processor(images=__A , return_tensors="""pt""" ).pixel_values.to(__A ) # make sure processor creates exact same pixel values assert torch.allclose(__A , __A ) original_model.to(__A ) hf_model.to(__A ) with torch.no_grad(): if "opt" in model_name: lowercase_ : Optional[Any] = original_model({"""image""": original_pixel_values, """text_input""": [""""""]} ).logits lowercase_ : Optional[Any] = hf_model(__A , __A ).logits else: lowercase_ : Any = original_model( {"""image""": original_pixel_values, """text_input""": ["""\n"""], """text_output""": ["""\n"""]} ).logits lowercase_ : Tuple = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) lowercase_ : int = hf_model(__A , __A , labels=__A ).logits assert original_logits.shape == logits.shape print("""First values of original logits:""" , original_logits[0, :3, :3] ) print("""First values of HF logits:""" , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": lowercase_ : Union[str, Any] = torch.tensor( [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=__A ) assert torch.allclose(logits[0, :3, :3] , __A , atol=1e-4 ) elif model_name == "blip2-flan-t5-xl-coco": lowercase_ : int = torch.tensor( [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=__A ) else: # cast to same type lowercase_ : Tuple = logits.dtype assert torch.allclose(original_logits.to(__A ) , __A , atol=1e-2 ) print("""Looks ok!""" ) print("""Generating a caption...""" ) lowercase_ : Union[str, Any] = """""" lowercase_ : Any = tokenizer(__A , return_tensors="""pt""" ).input_ids.to(__A ) lowercase_ : Any = original_model.generate({"""image""": original_pixel_values} ) lowercase_ : Tuple = hf_model.generate( __A , __A , do_sample=__A , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("""Original generation:""" , __A ) lowercase_ : List[str] = input_ids.shape[1] lowercase_ : Tuple = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=__A ) lowercase_ : Optional[int] = [text.strip() for text in output_text] print("""HF generation:""" , __A ) if pytorch_dump_folder_path is not None: processor.save_pretrained(__A ) hf_model.save_pretrained(__A ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": _lowercase : Dict = argparse.ArgumentParser() _lowercase : List[Any] = [ 'blip2-opt-2.7b', 'blip2-opt-6.7b', 'blip2-opt-2.7b-coco', 'blip2-opt-6.7b-coco', 'blip2-flan-t5-xl', 'blip2-flan-t5-xl-coco', 'blip2-flan-t5-xxl', ] parser.add_argument( "--model_name", default="blip2-opt-2.7b", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) _lowercase : Union[str, Any] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
239
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
'''simple docstring''' import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __SCREAMING_SNAKE_CASE : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def UpperCamelCase_ ( _UpperCAmelCase : Dict , _UpperCAmelCase : Tuple=None , _UpperCAmelCase : Optional[Any]=None , _UpperCAmelCase : Dict=None ) -> int: """simple docstring""" _UpperCAmelCase : str = True while ask_again: _UpperCAmelCase : int = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def UpperCamelCase_ ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Any=[] , _UpperCAmelCase : Optional[Any]=None , _UpperCAmelCase : Dict=0 ) -> Any: """simple docstring""" _UpperCAmelCase : Dict = BulletMenu(__A , __A ) _UpperCAmelCase : int = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def UpperCamelCase_ ( _UpperCAmelCase : List[Any] ) -> Dict: """simple docstring""" _UpperCAmelCase : Optional[int] = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def UpperCamelCase_ ( _UpperCAmelCase : Tuple ) -> List[Any]: """simple docstring""" _UpperCAmelCase : str = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def UpperCamelCase_ ( _UpperCAmelCase : str ) -> Dict: """simple docstring""" _UpperCAmelCase : int = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def UpperCamelCase_ ( _UpperCAmelCase : int ) -> str: """simple docstring""" _UpperCAmelCase : Union[str, Any] = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def UpperCamelCase_ ( _UpperCAmelCase : Union[str, Any] ) -> Any: """simple docstring""" _UpperCAmelCase : List[Any] = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def UpperCamelCase_ ( _UpperCAmelCase : Tuple ) -> Dict: """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCamelCase_ (argparse.RawDescriptionHelpFormatter ): '''simple docstring''' def _A ( self : Optional[Any] , A : Optional[Any] , A : str , A : Union[str, Any] , A : Optional[Any] ): _UpperCAmelCase : int = super()._format_usage(A , A , A , A ) _UpperCAmelCase : Any = usage.replace("<command> [<args>] " , "" ) return usage
31
'''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 ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\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 , *a , **a ): 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. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = 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. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = 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']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} 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`" ) UpperCamelCase__ = 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`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = 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." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments 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 , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = 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: UpperCamelCase__ = 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" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = 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. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "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: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "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 UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = 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 __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = 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: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0