code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from 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__)
130
class snake_case__(_UpperCamelCase ): """simple docstring""" pass class snake_case__(_UpperCamelCase ): """simple docstring""" pass class snake_case__: """simple docstring""" def __init__( self : Optional[Any] ): lowercase__ : List[Any] = [ [], [], [], ] def snake_case ( self : Tuple , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): try: if len(self.queues[priority] ) >= 100: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(SCREAMING_SNAKE_CASE ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def snake_case ( self : List[str] ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self : Dict ): return "\n".join(f"""Priority {i}: {q}""" for i, q in enumerate(self.queues ) ) class snake_case__: """simple docstring""" def __init__( self : List[str] ): lowercase__ : Tuple = [] def snake_case ( self : List[str] , SCREAMING_SNAKE_CASE : int ): if len(self.queue ) == 100: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(SCREAMING_SNAKE_CASE ) def snake_case ( self : Union[str, Any] ): if not self.queue: raise UnderFlowError("The queue is empty" ) else: lowercase__ : Optional[int] = min(self.queue ) self.queue.remove(SCREAMING_SNAKE_CASE ) return data def __str__( self : Any ): return str(self.queue ) def __lowerCamelCase ( ): """simple docstring""" lowercase__ : Any = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(lowerCamelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowerCamelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def __lowerCamelCase ( ): """simple docstring""" lowercase__ : Any = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(lowerCamelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowerCamelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
130
1
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 ( snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : List[str] , snake_case__ : Optional[Any] , snake_case__ : Any ) -> str: # Load configuration defined in the metadata file with open(snake_case__ ) as metadata_file: UpperCamelCase : List[str] = json.load(snake_case__ ) UpperCamelCase : Union[str, Any] = LukeConfig(use_entity_aware_attention=snake_case__ , **metadata['model_config'] ) # Load in the weights from the checkpoint_path UpperCamelCase : Any = torch.load(snake_case__ , map_location='cpu' )['module'] # Load the entity vocab file UpperCamelCase : Optional[Any] = load_original_entity_vocab(snake_case__ ) # add an entry for [MASK2] UpperCamelCase : Any = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase : str = XLMRobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase : Tuple = AddedToken('<ent>' , lstrip=snake_case__ , rstrip=snake_case__ ) UpperCamelCase : Optional[int] = AddedToken('<ent2>' , lstrip=snake_case__ , rstrip=snake_case__ ) 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(snake_case__ ) with open(os.path.join(snake_case__ , 'tokenizer_config.json' ) , 'r' ) as f: UpperCamelCase : int = json.load(snake_case__ ) UpperCamelCase : List[Any] = 'MLukeTokenizer' with open(os.path.join(snake_case__ , 'tokenizer_config.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) with open(os.path.join(snake_case__ , MLukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) UpperCamelCase : Union[str, Any] = MLukeTokenizer.from_pretrained(snake_case__ ) # Initialize the embeddings of the special tokens UpperCamelCase : List[str] = tokenizer.convert_tokens_to_ids(['@'] )[0] UpperCamelCase : List[Any] = tokenizer.convert_tokens_to_ids(['#'] )[0] UpperCamelCase : int = state_dict['embeddings.word_embeddings.weight'] UpperCamelCase : Optional[Any] = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase : Tuple = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase : Optional[int] = 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 : Tuple = state_dict[bias_name] UpperCamelCase : List[Any] = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase : str = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase : Union[str, Any] = 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 : Optional[int] = F"""encoder.layer.{layer_index}.attention.self.""" UpperCamelCase : List[str] = state_dict[prefix + matrix_name] UpperCamelCase : Optional[Any] = state_dict[prefix + matrix_name] UpperCamelCase : Union[str, Any] = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase : Any = state_dict['entity_embeddings.entity_embeddings.weight'] UpperCamelCase : str = entity_emb[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase : Optional[Any] = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase : Any = state_dict['entity_predictions.bias'] UpperCamelCase : Tuple = entity_prediction_bias[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase : Tuple = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase : Tuple = LukeForMaskedLM(config=snake_case__ ).eval() state_dict.pop('entity_predictions.decoder.weight' ) state_dict.pop('lm_head.decoder.weight' ) state_dict.pop('lm_head.decoder.bias' ) UpperCamelCase : str = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('lm_head' ) or key.startswith('entity_predictions' )): UpperCamelCase : Optional[int] = state_dict[key] else: UpperCamelCase : List[Any] = state_dict[key] UpperCamelCase : int = model.load_state_dict(snake_case__ , strict=snake_case__ ) if set(snake_case__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F"""Unexpected unexpected_keys: {unexpected_keys}""" ) if set(snake_case__ ) != { "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 : int = MLukeTokenizer.from_pretrained(snake_case__ , task='entity_classification' ) UpperCamelCase : str = 'ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).' UpperCamelCase : int = (0, 9) UpperCamelCase : Optional[Any] = tokenizer(snake_case__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase : str = model(**snake_case__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase : Optional[int] = torch.Size((1, 33, 768) ) UpperCamelCase : Union[str, Any] = 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] , snake_case__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase : Tuple = torch.Size((1, 1, 768) ) UpperCamelCase : Optional[int] = 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] , snake_case__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase : str = MLukeTokenizer.from_pretrained(snake_case__ ) UpperCamelCase : int = 'Tokyo is the capital of <mask>.' UpperCamelCase : str = (24, 30) UpperCamelCase : List[str] = tokenizer(snake_case__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase : Any = model(**snake_case__ ) UpperCamelCase : Tuple = encoding['input_ids'][0].tolist() UpperCamelCase : int = input_ids.index(tokenizer.convert_tokens_to_ids('<mask>' ) ) UpperCamelCase : Dict = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(snake_case__ ) UpperCamelCase : List[Any] = outputs.entity_logits[0][0].argmax().item() UpperCamelCase : Optional[int] = [ 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(snake_case__ ) ) model.save_pretrained(snake_case__ ) def UpperCamelCase ( snake_case__ : List[str] ) -> Optional[Any]: UpperCamelCase : Dict = ['[MASK]', '[PAD]', '[UNK]'] UpperCamelCase : Optional[Any] = [json.loads(snake_case__ ) for line in open(snake_case__ )] UpperCamelCase : Optional[int] = {} for entry in data: UpperCamelCase : Tuple = entry['id'] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase : int = entity_id break UpperCamelCase : Union[str, Any] = F"""{language}:{entity_name}""" UpperCamelCase : str = entity_id return new_mapping if __name__ == "__main__": __UpperCAmelCase = 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.''' ) __UpperCAmelCase = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
371
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') __UpperCAmelCase , __UpperCAmelCase = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') __UpperCAmelCase = rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: __UpperCAmelCase = rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) __UpperCAmelCase = args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([F"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([F"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
103
0
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" if b == 0: return 1 if (b % 2) == 0: return actual_power(lowercase , int(b / 2 ) ) * actual_power(lowercase , int(b / 2 ) ) else: return a * actual_power(lowercase , int(b / 2 ) ) * actual_power(lowercase , int(b / 2 ) ) def _A ( lowercase , lowercase ): """simple docstring""" if b < 0: return 1 / actual_power(lowercase , lowercase ) return actual_power(lowercase , lowercase ) if __name__ == "__main__": print(power(-2, -3))
81
def UpperCAmelCase_ ( _A ): '''simple docstring''' return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
314
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 AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ : str = logging.get_logger(__name__) lowerCAmelCase__ : Tuple = {'vocab_file': 'sentencepiece.bpe.model'} lowerCAmelCase__ : Union[str, Any] = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } lowerCAmelCase__ : List[str] = { 'camembert-base': 5_12, } lowerCAmelCase__ : int = '▁' class SCREAMING_SNAKE_CASE__ ( snake_case__ ): """simple docstring""" SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE = ['''input_ids''', '''attention_mask'''] def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple="<s>" , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : List[Any]="</s>" , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : Union[str, Any]="<unk>" , UpperCAmelCase_ : str="<pad>" , UpperCAmelCase_ : Union[str, Any]="<mask>" , UpperCAmelCase_ : Dict=["<s>NOTUSED", "</s>NOTUSED"] , UpperCAmelCase_ : Tuple = None , **UpperCAmelCase_ : List[str] , ): """simple docstring""" __UpperCAmelCase : List[Any] = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else mask_token __UpperCAmelCase : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_snake_case , eos_token=_snake_case , unk_token=_snake_case , sep_token=_snake_case , cls_token=_snake_case , pad_token=_snake_case , mask_token=_snake_case , additional_special_tokens=_snake_case , sp_model_kwargs=self.sp_model_kwargs , **_snake_case , ) __UpperCAmelCase : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_snake_case ) ) __UpperCAmelCase : Any = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __UpperCAmelCase : List[Any] = {"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3} __UpperCAmelCase : str = len(self.fairseq_tokens_to_ids ) __UpperCAmelCase : Optional[int] = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __UpperCAmelCase : List[str] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCamelCase_ ( self : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCAmelCase : Optional[Any] = [self.cls_token_id] __UpperCAmelCase : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase_ ( self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : List[str] = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_snake_case , token_ids_a=_snake_case , already_has_special_tokens=_snake_case ) if token_ids_a is None: return [1] + ([0] * len(_snake_case )) + [1] return [1] + ([0] * len(_snake_case )) + [1, 1] + ([0] * len(_snake_case )) + [1] def lowerCamelCase_ ( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] = None ): """simple docstring""" __UpperCAmelCase : int = [self.sep_token_id] __UpperCAmelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCamelCase_ ( self : Any ): """simple docstring""" return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" __UpperCAmelCase : int = {self.convert_ids_to_tokens(_snake_case ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase_ ( self : Optional[Any] , UpperCAmelCase_ : List[str] ): """simple docstring""" return self.sp_model.encode(_snake_case , out_type=_snake_case ) def lowerCamelCase_ ( self : Any , UpperCAmelCase_ : int ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_snake_case ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_snake_case ) def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase_ : Tuple ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def lowerCamelCase_ ( self : Dict , UpperCAmelCase_ : Union[str, Any] ): """simple docstring""" __UpperCAmelCase : Any = [] __UpperCAmelCase : Optional[int] = "" __UpperCAmelCase : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_snake_case ) + token __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : int = [] else: current_sub_tokens.append(_snake_case ) __UpperCAmelCase : Union[str, Any] = False out_string += self.sp_model.decode(_snake_case ) return out_string.strip() def __getstate__( self : Optional[Any] ): """simple docstring""" __UpperCAmelCase : Optional[int] = self.__dict__.copy() __UpperCAmelCase : Dict = None return state def __setstate__( self : Optional[Any] , UpperCAmelCase_ : str ): """simple docstring""" __UpperCAmelCase : str = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __UpperCAmelCase : List[str] = {} __UpperCAmelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase_ ( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Any = None ): """simple docstring""" if not os.path.isdir(_snake_case ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return __UpperCAmelCase : Any = os.path.join( _snake_case , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_snake_case ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _snake_case ) elif not os.path.isfile(self.vocab_file ): with open(_snake_case , "wb" ) as fi: __UpperCAmelCase : Any = self.sp_model.serialized_model_proto() fi.write(_snake_case ) return (out_vocab_file,)
361
'''simple docstring''' from heapq import heappop, heappush import numpy as np def __UpperCamelCase ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, ): __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = grid.shape __UpperCAmelCase : List[str] = [-1, 1, 0, 0] __UpperCAmelCase : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __UpperCAmelCase , __UpperCAmelCase : Tuple = [(0, source)], set() __UpperCAmelCase : Any = np.full((rows, cols), np.inf ) __UpperCAmelCase : List[str] = 0 __UpperCAmelCase : Union[str, Any] = np.empty((rows, cols), dtype=_UpperCAmelCase ) __UpperCAmelCase : Any = None while queue: ((__UpperCAmelCase) , (__UpperCAmelCase)) : Optional[Any] = heappop(_UpperCAmelCase ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __UpperCAmelCase : int = [] while (x, y) != source: path.append((x, y) ) __UpperCAmelCase , __UpperCAmelCase : Tuple = predecessors[x, y] path.append(_UpperCAmelCase ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(_UpperCAmelCase ) ): __UpperCAmelCase , __UpperCAmelCase : int = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __UpperCAmelCase : Optional[Any] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(_UpperCAmelCase, (dist + 1, (nx, ny)) ) __UpperCAmelCase : List[str] = dist + 1 __UpperCAmelCase : int = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
37
0
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ): """simple docstring""" lowercase_ : str = StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) lowercase_ : int = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler('''sample_euler''' ) lowercase_ : int = '''A painting of a squirrel eating a burger''' lowercase_ : Optional[int] = torch.manual_seed(0 ) lowercase_ : Optional[Any] = sd_pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) lowercase_ : str = output.images lowercase_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowercase_ : str = np.array([0.0_447, 0.0_492, 0.0_468, 0.0_408, 0.0_383, 0.0_408, 0.0_354, 0.0_380, 0.0_339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self ): """simple docstring""" lowercase_ : Any = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) lowercase_ : Optional[int] = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler('''sample_euler''' ) lowercase_ : Optional[int] = '''A painting of a squirrel eating a burger''' lowercase_ : List[Any] = torch.manual_seed(0 ) lowercase_ : Optional[int] = sd_pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) lowercase_ : Any = output.images lowercase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowercase_ : str = np.array([0.1_237, 0.1_320, 0.1_438, 0.1_359, 0.1_390, 0.1_132, 0.1_277, 0.1_175, 0.1_112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self ): """simple docstring""" lowercase_ : str = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) lowercase_ : Optional[Any] = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler('''sample_dpmpp_2m''' ) lowercase_ : List[Any] = '''A painting of a squirrel eating a burger''' lowercase_ : int = torch.manual_seed(0 ) lowercase_ : Dict = sd_pipe( [prompt] , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=15 , output_type='''np''' , use_karras_sigmas=__SCREAMING_SNAKE_CASE , ) lowercase_ : Union[str, Any] = output.images lowercase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowercase_ : Optional[int] = np.array( [0.11_381_689, 0.12_112_921, 0.1_389_457, 0.12_549_606, 0.1_244_964, 0.10_831_517, 0.11_562_866, 0.10_867_816, 0.10_499_048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
93
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = fname.split(os.path.sep )[-1] return re.search(R'^(.*)_\d+\.jpg$' , lowercase_ ).groups()[0] class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :List[str] , lowercase_ :Dict , lowercase_ :List[str]=None , lowercase_ :Optional[Any]=None ) -> Optional[int]: UpperCAmelCase = file_names UpperCAmelCase = image_transform UpperCAmelCase = label_to_id def __len__( self :Optional[int] ) -> Optional[Any]: return len(self.file_names ) def __getitem__( self :int , lowercase_ :str ) -> List[str]: UpperCAmelCase = self.file_names[idx] UpperCAmelCase = PIL.Image.open(lowercase_ ) UpperCAmelCase = raw_image.convert('RGB' ) if self.image_transform is not None: UpperCAmelCase = self.image_transform(lowercase_ ) UpperCAmelCase = extract_label(lowercase_ ) if self.label_to_id is not None: UpperCAmelCase = self.label_to_id[label] return {"image": image, "label": label} def _lowerCAmelCase ( lowercase_ , lowercase_ ): # Initialize accelerator if args.with_tracking: UpperCAmelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir ) else: UpperCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase = config['lr'] UpperCAmelCase = int(config['num_epochs'] ) UpperCAmelCase = int(config['seed'] ) UpperCAmelCase = int(config['batch_size'] ) UpperCAmelCase = config['image_size'] if not isinstance(lowercase_ , (list, tuple) ): UpperCAmelCase = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , 'isdigit' ): if args.checkpointing_steps == "epoch": UpperCAmelCase = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): UpperCAmelCase = int(args.checkpointing_steps ) else: raise ValueError( F"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.""" ) else: UpperCAmelCase = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: UpperCAmelCase = os.path.split(lowercase_ )[-1].split('.' )[0] accelerator.init_trackers(lowercase_ , lowercase_ ) # Grab all the image filenames UpperCAmelCase = [os.path.join(args.data_dir , lowercase_ ) for fname in os.listdir(args.data_dir ) if fname.endswith('.jpg' )] # Build the label correspondences UpperCAmelCase = [extract_label(lowercase_ ) for fname in file_names] UpperCAmelCase = list(set(lowercase_ ) ) id_to_label.sort() UpperCAmelCase = {lbl: i for i, lbl in enumerate(lowercase_ )} # Set the seed before splitting the data. np.random.seed(lowercase_ ) torch.manual_seed(lowercase_ ) torch.cuda.manual_seed_all(lowercase_ ) # Split our filenames between train and validation UpperCAmelCase = np.random.permutation(len(lowercase_ ) ) UpperCAmelCase = int(0.8 * len(lowercase_ ) ) UpperCAmelCase = random_perm[:cut] UpperCAmelCase = random_perm[cut:] # For training we use a simple RandomResizedCrop UpperCAmelCase = Compose([RandomResizedCrop(lowercase_ , scale=(0.5, 1.0) ), ToTensor()] ) UpperCAmelCase = PetsDataset( [file_names[i] for i in train_split] , image_transform=lowercase_ , label_to_id=lowercase_ ) # For evaluation, we use a deterministic Resize UpperCAmelCase = Compose([Resize(lowercase_ ), ToTensor()] ) UpperCAmelCase = PetsDataset([file_names[i] for i in eval_split] , image_transform=lowercase_ , label_to_id=lowercase_ ) # Instantiate dataloaders. UpperCAmelCase = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) UpperCAmelCase = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase = create_model('resnet50d' , pretrained=lowercase_ , num_classes=len(lowercase_ ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCAmelCase = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): UpperCAmelCase = False for param in model.get_classifier().parameters(): UpperCAmelCase = True # We normalize the batches of images to be a bit faster. UpperCAmelCase = torch.tensor(model.default_cfg['mean'] )[None, :, None, None].to(accelerator.device ) UpperCAmelCase = torch.tensor(model.default_cfg['std'] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer UpperCAmelCase = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler UpperCAmelCase = OneCycleLR(optimizer=lowercase_ , max_lr=lowercase_ , epochs=lowercase_ , steps_per_epoch=len(lowercase_ ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = accelerator.prepare( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase = 0 # We also need to keep track of the starting epoch so files are named properly UpperCAmelCase = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}""" ) accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint UpperCAmelCase = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) UpperCAmelCase = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` UpperCAmelCase = os.path.splitext(lowercase_ )[0] if "epoch" in training_difference: UpperCAmelCase = int(training_difference.replace('epoch_' , '' ) ) + 1 UpperCAmelCase = None else: UpperCAmelCase = int(training_difference.replace('step_' , '' ) ) UpperCAmelCase = resume_step // len(lowercase_ ) resume_step -= starting_epoch * len(lowercase_ ) # Now we train the model for epoch in range(lowercase_ , lowercase_ ): model.train() if args.with_tracking: UpperCAmelCase = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step UpperCAmelCase = accelerator.skip_first_batches(lowercase_ , lowercase_ ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader UpperCAmelCase = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. UpperCAmelCase = {k: v.to(accelerator.device ) for k, v in batch.items()} UpperCAmelCase = (batch['image'] - mean) / std UpperCAmelCase = model(lowercase_ ) UpperCAmelCase = torch.nn.functional.cross_entropy(lowercase_ , batch['label'] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(lowercase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = F"""step_{overall_step}""" if overall_step % checkpointing_steps == 0: if args.output_dir is not None: UpperCAmelCase = os.path.join(args.output_dir , lowercase_ ) accelerator.save_state(lowercase_ ) model.eval() UpperCAmelCase = 0 UpperCAmelCase = 0 for step, batch in enumerate(lowercase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. UpperCAmelCase = {k: v.to(accelerator.device ) for k, v in batch.items()} UpperCAmelCase = (batch['image'] - mean) / std with torch.no_grad(): UpperCAmelCase = model(lowercase_ ) UpperCAmelCase = outputs.argmax(dim=-1 ) UpperCAmelCase , UpperCAmelCase = accelerator.gather_for_metrics((predictions, batch['label']) ) UpperCAmelCase = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() UpperCAmelCase = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}: {100 * eval_metric:.2f}""" ) if args.with_tracking: accelerator.log( { 'accuracy': 100 * eval_metric, 'train_loss': total_loss.item() / len(lowercase_ ), 'epoch': epoch, } , step=lowercase_ , ) if checkpointing_steps == "epoch": UpperCAmelCase = F"""epoch_{epoch}""" if args.output_dir is not None: UpperCAmelCase = os.path.join(args.output_dir , lowercase_ ) accelerator.save_state(lowercase_ ) if args.with_tracking: accelerator.end_training() def _lowerCAmelCase ( ): UpperCAmelCase = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument('--data_dir' , required=lowercase_ , help='The data folder on disk.' ) parser.add_argument('--fp16' , action='store_true' , help='If passed, will use FP16 training.' ) parser.add_argument( '--mixed_precision' , type=lowercase_ , default=lowercase_ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) parser.add_argument( '--checkpointing_steps' , type=lowercase_ , default=lowercase_ , help='Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.' , ) parser.add_argument( '--output_dir' , type=lowercase_ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--resume_from_checkpoint' , type=lowercase_ , default=lowercase_ , help='If the training should continue from a checkpoint folder.' , ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=lowercase_ , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = {'lr': 3e-2, 'num_epochs': 3, 'seed': 42, 'batch_size': 64, 'image_size': 224} training_function(lowercase_ , lowercase_ ) if __name__ == "__main__": main()
78
0
from typing import List import numpy as np def lowerCAmelCase_ ( __lowerCAmelCase )-> int: '''simple docstring''' UpperCAmelCase : Any ={key: len(_snake_case ) for key, value in gen_kwargs.items() if isinstance(_snake_case , _snake_case )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( '''Sharding is ambiguous for this dataset: ''' + '''we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n''' + '''\n'''.join(f'''\t- key {key} has length {length}''' for key, length in lists_lengths.items() ) + '''\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ''' + '''and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.''' ) ) UpperCAmelCase : int =max(lists_lengths.values() , default=0 ) return max(1 , _snake_case ) def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> List[range]: '''simple docstring''' UpperCAmelCase : Dict =[] for group_idx in range(_snake_case ): UpperCAmelCase : List[str] =num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break UpperCAmelCase : Tuple =shards_indices_per_group[-1].stop if shards_indices_per_group else 0 UpperCAmelCase : Optional[int] =range(_snake_case , start + num_shards_to_add ) shards_indices_per_group.append(_snake_case ) return shards_indices_per_group def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> List[dict]: '''simple docstring''' UpperCAmelCase : int =_number_of_shards_in_gen_kwargs(_snake_case ) if num_shards == 1: return [dict(_snake_case )] else: UpperCAmelCase : str =_distribute_shards(num_shards=_snake_case , max_num_jobs=_snake_case ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(_snake_case , _snake_case ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(_snake_case ) ) ] def lowerCAmelCase_ ( __lowerCAmelCase )-> dict: '''simple docstring''' return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , _snake_case ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> dict: '''simple docstring''' UpperCAmelCase : Optional[Any] ={len(_snake_case ) for value in gen_kwargs.values() if isinstance(_snake_case , _snake_case )} UpperCAmelCase : int ={} for size in list_sizes: UpperCAmelCase : List[Any] =list(range(_snake_case ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes UpperCAmelCase : Any =dict(_snake_case ) for key, value in shuffled_kwargs.items(): if isinstance(_snake_case , _snake_case ): UpperCAmelCase : Dict =[value[i] for i in indices_per_size[len(_snake_case )]] return shuffled_kwargs
369
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __snake_case ( lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = ["""image_processor""", """tokenizer"""] __lowerCamelCase : Union[str, Any] = """CLIPImageProcessor""" __lowerCamelCase : Any = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self , snake_case__=None , snake_case__=None , **snake_case__ ) -> List[str]: '''simple docstring''' UpperCAmelCase : Optional[int] =None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , snake_case__ , ) UpperCAmelCase : int =kwargs.pop('''feature_extractor''' ) UpperCAmelCase : Tuple =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__(snake_case__ , snake_case__ ) def __call__( self , snake_case__=None , snake_case__=None , snake_case__=None , **snake_case__ ) -> Optional[Any]: '''simple docstring''' if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: UpperCAmelCase : List[Any] =self.tokenizer(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if images is not None: UpperCAmelCase : Tuple =self.image_processor(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if text is not None and images is not None: UpperCAmelCase : List[Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**snake_case__ ) , tensor_type=snake_case__ ) def UpperCAmelCase__ ( self , *snake_case__ , **snake_case__ ) -> Optional[int]: '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def UpperCAmelCase__ ( self , *snake_case__ , **snake_case__ ) -> List[Any]: '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' UpperCAmelCase : List[str] =self.tokenizer.model_input_names UpperCAmelCase : Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , snake_case__ , ) return self.image_processor_class @property def UpperCAmelCase__ ( self ) -> Tuple: '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , snake_case__ , ) return self.image_processor
78
0
import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _lowercase ( lowercase__ , unittest.TestCase): """simple docstring""" A__ = LEDTokenizer A__ = LEDTokenizerFast A__ = True def lowerCAmelCase ( self : Tuple ): '''simple docstring''' super().setUp() lowerCamelCase__ : Optional[int] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] lowerCamelCase__ : str = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) lowerCamelCase__ : Any = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] lowerCamelCase__ : Optional[int] = {"unk_token": "<unk>"} lowerCamelCase__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowerCamelCase__ : List[str] = 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(__lowerCamelCase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__lowerCamelCase ) ) def lowerCAmelCase ( self : Union[str, Any] , **__lowerCamelCase : Optional[Any] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def lowerCAmelCase ( self : Tuple , **__lowerCamelCase : List[str] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def lowerCAmelCase ( self : str , __lowerCamelCase : Optional[int] ): '''simple docstring''' return "lower newer", "lower newer" @cached_property def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' return LEDTokenizer.from_pretrained("allenai/led-base-16384" ) @cached_property def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return LEDTokenizerFast.from_pretrained("allenai/led-base-16384" ) @require_torch def lowerCAmelCase ( self : Tuple ): '''simple docstring''' lowerCamelCase__ : str = ["A long paragraph for summarization.", "Another paragraph for summarization."] lowerCamelCase__ : Tuple = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase__ : List[str] = tokenizer(__lowerCamelCase , max_length=len(__lowerCamelCase ) , padding=__lowerCamelCase , return_tensors="pt" ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) lowerCamelCase__ : Optional[Any] = batch.input_ids.tolist()[0] self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) @require_torch def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCamelCase__ : List[str] = ["A long paragraph for summarization.", "Another paragraph for summarization."] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase__ : List[Any] = tokenizer(__lowerCamelCase , padding=__lowerCamelCase , return_tensors="pt" ) self.assertIn("input_ids" , __lowerCamelCase ) self.assertIn("attention_mask" , __lowerCamelCase ) self.assertNotIn("labels" , __lowerCamelCase ) self.assertNotIn("decoder_attention_mask" , __lowerCamelCase ) @require_torch def lowerCAmelCase ( self : List[str] ): '''simple docstring''' lowerCamelCase__ : Any = [ "Summary of the text.", "Another summary.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase__ : Union[str, Any] = tokenizer(text_target=__lowerCamelCase , max_length=32 , padding="max_length" , return_tensors="pt" ) self.assertEqual(32 , targets["input_ids"].shape[1] ) @require_torch def lowerCAmelCase ( self : List[str] ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase__ : Tuple = tokenizer( ["I am a small frog" * 1024, "I am a small frog"] , padding=__lowerCamelCase , truncation=__lowerCamelCase , return_tensors="pt" ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(batch.input_ids.shape , (2, 5122) ) @require_torch def lowerCAmelCase ( self : Any ): '''simple docstring''' lowerCamelCase__ : Dict = ["A long paragraph for summarization."] lowerCamelCase__ : List[Any] = [ "Summary of the text.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase__ : Dict = tokenizer(__lowerCamelCase , return_tensors="pt" ) lowerCamelCase__ : List[str] = tokenizer(text_target=__lowerCamelCase , return_tensors="pt" ) lowerCamelCase__ : List[str] = inputs["input_ids"] lowerCamelCase__ : Dict = targets["input_ids"] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def lowerCAmelCase ( self : int ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase__ : List[str] = ["Summary of the text.", "Another summary."] lowerCamelCase__ : List[Any] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] lowerCamelCase__ : int = tokenizer(__lowerCamelCase , padding=__lowerCamelCase ) lowerCamelCase__ : Union[str, Any] = [[0] * len(__lowerCamelCase ) for x in encoded_output["input_ids"]] lowerCamelCase__ : List[Any] = tokenizer.pad(__lowerCamelCase ) self.assertSequenceEqual(outputs["global_attention_mask"] , __lowerCamelCase ) def lowerCAmelCase ( self : int ): '''simple docstring''' pass def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): lowerCamelCase__ : str = self.rust_tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) lowerCamelCase__ : Union[str, Any] = self.tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) lowerCamelCase__ : int = "A, <mask> AllenNLP sentence." lowerCamelCase__ : Any = tokenizer_r.encode_plus(__lowerCamelCase , add_special_tokens=__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) lowerCamelCase__ : List[Any] = tokenizer_p.encode_plus(__lowerCamelCase , add_special_tokens=__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) ) self.assertEqual( sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , ) lowerCamelCase__ : str = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) lowerCamelCase__ : List[str] = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] ) self.assertSequenceEqual(tokens_p["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( __lowerCamelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( __lowerCamelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
184
from __future__ import annotations A : Union[str, Any] = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class _lowercase : """simple docstring""" def __init__( self : Tuple , __lowerCamelCase : dict[str, list[str]] , __lowerCamelCase : str ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = graph # mapping node to its parent in resulting breadth first tree lowerCamelCase__ : dict[str, str | None] = {} lowerCamelCase__ : Dict = source_vertex def lowerCAmelCase ( self : Any ): '''simple docstring''' lowerCamelCase__ : int = {self.source_vertex} lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : Dict = [self.source_vertex] # first in first out queue while queue: lowerCamelCase__ : Optional[int] = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowerCamelCase ) lowerCamelCase__ : List[str] = vertex queue.append(__lowerCamelCase ) def lowerCAmelCase ( self : Optional[Any] , __lowerCamelCase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex lowerCamelCase__ : Tuple = self.parent.get(__lowerCamelCase ) if target_vertex_parent is None: lowerCamelCase__ : Tuple = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowerCamelCase ) return self.shortest_path(__lowerCamelCase ) + f"->{target_vertex}" if __name__ == "__main__": A : List[str] = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
184
1
import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = torch.exp(_lowerCamelCase ) _a : Dict = torch.sum(_lowerCamelCase , dim=1 ) # sum of exp(x_i) _a : List[Any] = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(_lowerCamelCase ) - B / A class UpperCamelCase ( nn.Module ): def __init__( self : List[str] , UpperCAmelCase__ : str ) -> Optional[Any]: super().__init__() _a : Tuple = config.output_attentions _a : List[Any] = config.output_hidden_states _a : str = nn.ModuleList([BertLayer(UpperCAmelCase__ ) for _ in range(config.num_hidden_layers )] ) _a : Any = nn.ModuleList([BertHighway(UpperCAmelCase__ ) for _ in range(config.num_hidden_layers )] ) _a : int = [-1 for _ in range(config.num_hidden_layers )] def _lowercase ( self : str , UpperCAmelCase__ : int ) -> Optional[int]: if (type(UpperCAmelCase__ ) is float) or (type(UpperCAmelCase__ ) is int): for i in range(len(self.early_exit_entropy ) ): _a : int = x else: _a : Union[str, Any] = x def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Optional[Any]: _a : int = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def _lowercase ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : str=None , UpperCAmelCase__ : str=None , ) -> List[str]: _a : str = () _a : List[str] = () _a : Tuple = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _a : List[Any] = all_hidden_states + (hidden_states,) _a : str = layer_module( UpperCAmelCase__ , UpperCAmelCase__ , head_mask[i] , UpperCAmelCase__ , UpperCAmelCase__ ) _a : str = layer_outputs[0] if self.output_attentions: _a : Dict = all_attentions + (layer_outputs[1],) _a : int = (hidden_states,) if self.output_hidden_states: _a : Dict = current_outputs + (all_hidden_states,) if self.output_attentions: _a : Union[str, Any] = current_outputs + (all_attentions,) _a : Optional[int] = self.highway[i](UpperCAmelCase__ ) # logits, pooled_output if not self.training: _a : Dict = highway_exit[0] _a : str = entropy(UpperCAmelCase__ ) _a : List[Any] = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _a : str = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _a : Any = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(UpperCAmelCase__ , i + 1 ) else: _a : Optional[Any] = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _a : str = all_hidden_states + (hidden_states,) _a : Union[str, Any] = (hidden_states,) if self.output_hidden_states: _a : Any = outputs + (all_hidden_states,) if self.output_attentions: _a : Tuple = outputs + (all_attentions,) _a : Any = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( '''The Bert Model transformer with early exiting (DeeBERT). ''' , a__ , ) class UpperCamelCase ( a__ ): def __init__( self : int , UpperCAmelCase__ : Dict ) -> Optional[int]: super().__init__(UpperCAmelCase__ ) _a : Optional[int] = config _a : Dict = BertEmbeddings(UpperCAmelCase__ ) _a : Any = DeeBertEncoder(UpperCAmelCase__ ) _a : List[Any] = BertPooler(UpperCAmelCase__ ) self.init_weights() def _lowercase ( self : Optional[Any] ) -> List[Any]: self.encoder.init_highway_pooler(self.pooler ) def _lowercase ( self : List[str] ) -> Tuple: return self.embeddings.word_embeddings def _lowercase ( self : Dict , UpperCAmelCase__ : Tuple ) -> Dict: _a : Union[str, Any] = value def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : Any ) -> Any: for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(UpperCAmelCase__ ) @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Union[str, Any]=None , ) -> int: if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: _a : Optional[int] = input_ids.size() elif inputs_embeds is not None: _a : str = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) _a : Tuple = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _a : Optional[Any] = torch.ones(UpperCAmelCase__ , device=UpperCAmelCase__ ) if encoder_attention_mask is None: _a : Optional[int] = torch.ones(UpperCAmelCase__ , device=UpperCAmelCase__ ) if token_type_ids is None: _a : Dict = torch.zeros(UpperCAmelCase__ , dtype=torch.long , device=UpperCAmelCase__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _a : torch.Tensor = self.get_extended_attention_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _a : Optional[int] = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _a : Optional[Any] = encoder_attention_mask[:, None, None, :] _a : List[Any] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _a : Dict = (1.0 - encoder_extended_attention_mask) * -10000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _a : int = self.get_head_mask(UpperCAmelCase__ , self.config.num_hidden_layers ) _a : str = self.embeddings( input_ids=UpperCAmelCase__ , position_ids=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , inputs_embeds=UpperCAmelCase__ ) _a : Optional[Any] = self.encoder( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , head_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) _a : str = encoder_outputs[0] _a : Tuple = self.pooler(UpperCAmelCase__ ) _a : Tuple = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class UpperCamelCase ( a__ ): def __init__( self : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Optional[Any]: _a : str = message _a : Dict = exit_layer # start from 1! class UpperCamelCase ( nn.Module ): def __init__( self : str , UpperCAmelCase__ : int ) -> Tuple: super().__init__() _a : Union[str, Any] = BertPooler(UpperCAmelCase__ ) _a : Tuple = nn.Dropout(config.hidden_dropout_prob ) _a : str = nn.Linear(config.hidden_size , config.num_labels ) def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] ) -> Dict: # Pooler _a : Optional[Any] = encoder_outputs[0] _a : int = self.pooler(UpperCAmelCase__ ) # "return" pooler_output # BertModel _a : Union[str, Any] = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _a : Union[str, Any] = bmodel_output[1] _a : int = self.dropout(UpperCAmelCase__ ) _a : Dict = self.classifier(UpperCAmelCase__ ) return logits, pooled_output @add_start_docstrings( '''Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. ''' , a__ , ) class UpperCamelCase ( a__ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: super().__init__(UpperCAmelCase__ ) _a : str = config.num_labels _a : List[Any] = config.num_hidden_layers _a : Union[str, Any] = DeeBertModel(UpperCAmelCase__ ) _a : List[Any] = nn.Dropout(config.hidden_dropout_prob ) _a : str = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) def _lowercase ( self : List[str] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int=-1 , UpperCAmelCase__ : Optional[int]=False , ) -> List[Any]: _a : int = self.num_layers try: _a : Optional[Any] = self.bert( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , position_ids=UpperCAmelCase__ , head_mask=UpperCAmelCase__ , inputs_embeds=UpperCAmelCase__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _a : Any = outputs[1] _a : Tuple = self.dropout(UpperCAmelCase__ ) _a : Any = self.classifier(UpperCAmelCase__ ) _a : Dict = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _a : List[Any] = e.message _a : Optional[int] = e.exit_layer _a : Tuple = outputs[0] if not self.training: _a : Optional[int] = entropy(UpperCAmelCase__ ) _a : Any = [] _a : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression _a : Union[str, Any] = MSELoss() _a : Union[str, Any] = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _a : Any = CrossEntropyLoss() _a : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _a : int = [] for highway_exit in outputs[-1]: _a : List[Any] = highway_exit[0] if not self.training: highway_logits_all.append(UpperCAmelCase__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _a : int = MSELoss() _a : Any = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _a : Dict = CrossEntropyLoss() _a : List[str] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(UpperCAmelCase__ ) if train_highway: _a : Union[str, Any] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _a : Any = (loss,) + outputs if not self.training: _a : Any = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _a : int = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
370
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger() @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : List[nn.Module] = field(default_factory=snake_case_ ) UpperCamelCase : list = field(default_factory=snake_case_ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : Tensor ) -> Any: _a : int = len(list(m.modules() ) ) == 1 or isinstance(UpperCAmelCase__ , nn.Convad ) or isinstance(UpperCAmelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : Tensor ) -> Tuple: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCAmelCase__ ) [x.remove() for x in self.handles] return self @property def _lowercase ( self : Optional[int] ) -> int: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : nn.Module UpperCamelCase : int = 0 UpperCamelCase : List = field(default_factory=snake_case_ ) UpperCamelCase : List = field(default_factory=snake_case_ ) def __call__( self : Optional[Any] , UpperCAmelCase__ : Tensor ) -> Tuple: _a : Union[str, Any] = Tracker(self.dest )(UpperCAmelCase__ ).parametrized _a : List[Any] = Tracker(self.src )(UpperCAmelCase__ ).parametrized _a : Tuple = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.src_skip , UpperCAmelCase__ ) ) _a : Union[str, Any] = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.dest_skip , UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise Exception( f"""Numbers of operations are different. Source module has {len(UpperCAmelCase__ )} operations while""" f""" destination module has {len(UpperCAmelCase__ )}.""" ) for dest_m, src_m in zip(UpperCAmelCase__ , UpperCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = True ): '''simple docstring''' print(F"""Converting {name}...""" ) with torch.no_grad(): _a : List[str] = timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ).eval() _a : str = ResNetForImageClassification(UpperCamelCase__ ).eval() _a : List[str] = ModuleTransfer(src=UpperCamelCase__ , dest=UpperCamelCase__ ) _a : List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(UpperCamelCase__ ) assert torch.allclose(from_model(UpperCamelCase__ ) , our_model(UpperCamelCase__ ).logits ), "The model logits don't match the original one." _a : Dict = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(UpperCamelCase__ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=UpperCamelCase__ , ) # we can use the convnext one _a : Optional[Any] = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase__ , ) print(F"""Pushed {checkpoint_name}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = True ): '''simple docstring''' _a : Any = """imagenet-1k-id2label.json""" _a : Optional[int] = 1_0_0_0 _a : Any = (1, num_labels) _a : Union[str, Any] = """huggingface/label-files""" _a : Tuple = num_labels _a : Optional[int] = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) _a : Optional[Any] = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} _a : Any = idalabel _a : Tuple = {v: k for k, v in idalabel.items()} _a : List[str] = partial(UpperCamelCase__ , num_labels=UpperCamelCase__ , idalabel=UpperCamelCase__ , labelaid=UpperCamelCase__ ) _a : Union[str, Any] = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(UpperCamelCase__ , names_to_config[model_name] , UpperCamelCase__ , UpperCamelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return config, expected_shape if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported resnet* architecture,' ' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) _snake_case = parser.parse_args() _snake_case = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
324
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo SCREAMING_SNAKE_CASE__ : List[Any] = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" SCREAMING_SNAKE_CASE__ : Optional[int] = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" SCREAMING_SNAKE_CASE__ : Any = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : str ) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[List[List[str]]] , SCREAMING_SNAKE_CASE__ : List[List[str]] , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE__ , hypotheses=SCREAMING_SNAKE_CASE__ , min_len=SCREAMING_SNAKE_CASE__ , max_len=SCREAMING_SNAKE_CASE__ ) }
270
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
1
class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self : int , __A : List[str] ): # we need a list not a string, so do something to change the type snake_case__ : Dict = arr.split("," ) def _lowercase ( self : Union[str, Any] ): snake_case__ : Union[str, Any] = [int(self.array[0] )] * len(self.array ) snake_case__ : Optional[Any] = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): snake_case__ : Tuple = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) snake_case__ : Dict = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": __lowerCamelCase : Tuple = input("""please input some numbers:""") __lowerCamelCase : List[Any] = SubArray(whole_array) __lowerCamelCase : List[Any] = array.solve_sub_array() print(("""the results is:""", re))
286
from __future__ import annotations def SCREAMING_SNAKE_CASE ( snake_case_ : float , snake_case_ : float , snake_case_ : float ): if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0" ) if daily_interest_rate < 0: raise ValueError("daily_interest_rate must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return principal * daily_interest_rate * days_between_payments def SCREAMING_SNAKE_CASE ( snake_case_ : float , snake_case_ : float , snake_case_ : float , ): if number_of_compounding_periods <= 0: raise ValueError("number_of_compounding_periods must be > 0" ) if nominal_annual_interest_rate_percentage < 0: raise ValueError("nominal_annual_interest_rate_percentage must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def SCREAMING_SNAKE_CASE ( snake_case_ : float , snake_case_ : float , snake_case_ : float , ): if number_of_years <= 0: raise ValueError("number_of_years must be > 0" ) if nominal_annual_percentage_rate < 0: raise ValueError("nominal_annual_percentage_rate must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return compound_interest( snake_case_ , nominal_annual_percentage_rate / 365 , number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
286
1
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCAmelCase ( _UpperCamelCase : int ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =str(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =[n] for i in range(1 , len(_UpperCamelCase ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if len(str(_UpperCamelCase ) ) > 3: if not is_prime(int(str(_UpperCamelCase )[-3:] ) ) or not is_prime(int(str(_UpperCamelCase )[:3] ) ): return False return True def _lowerCAmelCase ( _UpperCamelCase : int = 11 ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =13 while len(_UpperCamelCase ) != count: if validate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =list_truncated_nums(_UpperCamelCase ) if all(is_prime(_UpperCamelCase ) for i in list_nums ): list_truncated_primes.append(_UpperCamelCase ) num += 2 return list_truncated_primes def _lowerCAmelCase ( ) -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(1_1)) = }''')
47
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(_a ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] if embedding_dimension and num_static_categorical_features > 0: if len(_a ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
47
1
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py lowercase : Tuple = """src/diffusers""" lowercase : Dict = """.""" # This is to make sure the diffusers module imported is the one in the repo. lowercase : Union[str, Any] = importlib.util.spec_from_file_location( """diffusers""", os.path.join(DIFFUSERS_PATH, """__init__.py"""), submodule_search_locations=[DIFFUSERS_PATH], ) lowercase : List[Any] = spec.loader.load_module() def A_ ( A__ , A__ ) -> Optional[Any]: return line.startswith(_A ) or len(_A ) <= 1 or re.search(R'^\s*\)(\s*->.*:|:)\s*$' , _A ) is not None def A_ ( A__ ) -> int: a__ : Optional[Any] = object_name.split('.' ) a__ : Optional[Any] = 0 # First let's find the module where our object lives. a__ : Dict = parts[i] while i < len(_A ) and not os.path.isfile(os.path.join(_A , F'{module}.py' ) ): i += 1 if i < len(_A ): a__ : Dict = os.path.join(_A , parts[i] ) if i >= len(_A ): raise ValueError(F'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(_A , F'{module}.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: a__ : List[Any] = f.readlines() # Now let's find the class / func in the code! a__ : Dict = '' a__ : Tuple = 0 for name in parts[i + 1 :]: while ( line_index < len(_A ) and re.search(RF'^{indent}(class|def)\s+{name}(\(|\:)' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(_A ): raise ValueError(F' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). a__ : Tuple = line_index while line_index < len(_A ) and _should_continue(lines[line_index] , _A ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 a__ : Dict = lines[start_index:line_index] return "".join(_A ) lowercase : Union[str, Any] = re.compile(r"""^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)""") lowercase : Optional[int] = re.compile(r"""^\s*(\S+)->(\S+)(\s+.*|$)""") lowercase : str = re.compile(r"""<FILL\s+[^>]*>""") def A_ ( A__ ) -> Optional[Any]: a__ : Optional[int] = code.split('\n' ) a__ : Optional[Any] = 0 while idx < len(_A ) and len(lines[idx] ) == 0: idx += 1 if idx < len(_A ): return re.search(R'^(\s*)\S' , lines[idx] ).groups()[0] return "" def A_ ( A__ ) -> List[Any]: a__ : Optional[Any] = len(get_indent(_A ) ) > 0 if has_indent: a__ : int = F'class Bla:\n{code}' a__ : Union[str, Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=_A ) a__ : List[str] = black.format_str(_A , mode=_A ) a__ : List[str] = style_docstrings_in_code(_A ) return result[len('class Bla:\n' ) :] if has_indent else result def A_ ( A__ , A__=False ) -> int: with open(_A , 'r' , encoding='utf-8' , newline='\n' ) as f: a__ : str = f.readlines() a__ : Union[str, Any] = [] a__ : str = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(_A ): a__ : List[str] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. a__ : Optional[Any] = search.groups() a__ : Optional[int] = find_code_in_diffusers(_A ) a__ : List[Any] = get_indent(_A ) a__ : str = line_index + 1 if indent == theoretical_indent else line_index + 2 a__ : Union[str, Any] = theoretical_indent a__ : Dict = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. a__ : Optional[int] = True while line_index < len(_A ) and should_continue: line_index += 1 if line_index >= len(_A ): break a__ : Any = lines[line_index] a__ : Optional[int] = _should_continue(_A , _A ) and re.search(F'^{indent}# End copy' , _A ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 a__ : Union[str, Any] = lines[start_index:line_index] a__ : Optional[int] = ''.join(_A ) # Remove any nested `Copied from` comments to avoid circular copies a__ : List[Any] = [line for line in theoretical_code.split('\n' ) if _re_copy_warning.search(_A ) is None] a__ : List[Any] = '\n'.join(_A ) # Before comparing, use the `replace_pattern` on the original code. if len(_A ) > 0: a__ : List[Any] = replace_pattern.replace('with' , '' ).split(',' ) a__ : Union[str, Any] = [_re_replace_pattern.search(_A ) for p in patterns] for pattern in patterns: if pattern is None: continue a__ : Tuple = pattern.groups() a__ : Optional[Any] = re.sub(_A , _A , _A ) if option.strip() == "all-casing": a__ : Any = re.sub(obja.lower() , obja.lower() , _A ) a__ : Optional[int] = re.sub(obja.upper() , obja.upper() , _A ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line a__ : Any = blackify(lines[start_index - 1] + theoretical_code ) a__ : Optional[int] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: a__ : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] a__ : str = start_index + 1 if overwrite and len(_A ) > 0: # Warn the user a file has been modified. print(F'Detected changes, rewriting {filename}.' ) with open(_A , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(_A ) return diffs def A_ ( A__ = False ) -> Optional[Any]: a__ : Union[str, Any] = glob.glob(os.path.join(_A , '**/*.py' ) , recursive=_A ) a__ : Union[str, Any] = [] for filename in all_files: a__ : int = is_copy_consistent(_A , _A ) diffs += [F'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(_A ) > 0: a__ : Any = '\n'.join(_A ) raise Exception( 'Found the following copy inconsistencies:\n' + diff + '\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.' ) if __name__ == "__main__": lowercase : Any = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") lowercase : Tuple = parser.parse_args() check_copies(args.fix_and_overwrite)
353
import pickle import numpy as np from matplotlib import pyplot as plt class A__ : """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase=0.2 , lowercase=0.2) -> Any: '''simple docstring''' a__ : Tuple = bp_numa a__ : Union[str, Any] = bp_numa a__ : Optional[int] = bp_numa a__ : Optional[int] = conva_get[:2] a__ : Optional[Any] = conva_get[2] a__ : Optional[int] = size_pa a__ : Union[str, Any] = rate_w a__ : Dict = rate_t a__ : int = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5) for i in range(self.conva[1]) ] a__ : Optional[int] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5) a__ : Optional[int] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5) a__ : Any = -2 * np.random.rand(self.conva[1]) + 1 a__ : Optional[Any] = -2 * np.random.rand(self.num_bpa) + 1 a__ : Optional[int] = -2 * np.random.rand(self.num_bpa) + 1 def __lowercase ( self , lowercase) -> List[Any]: '''simple docstring''' a__ : Optional[Any] = { 'num_bp1': self.num_bpa, 'num_bp2': self.num_bpa, 'num_bp3': self.num_bpa, 'conv1': self.conva, 'step_conv1': self.step_conva, 'size_pooling1': self.size_poolinga, 'rate_weight': self.rate_weight, 'rate_thre': self.rate_thre, 'w_conv1': self.w_conva, 'wkj': self.wkj, 'vji': self.vji, 'thre_conv1': self.thre_conva, 'thre_bp2': self.thre_bpa, 'thre_bp3': self.thre_bpa, } with open(lowercase , 'wb') as f: pickle.dump(lowercase , lowercase) print(F'Model saved: {save_path}') @classmethod def __lowercase ( cls , lowercase) -> Any: '''simple docstring''' with open(lowercase , 'rb') as f: a__ : Any = pickle.load(lowercase) # noqa: S301 a__ : Dict = model_dic.get('conv1') conv_get.append(model_dic.get('step_conv1')) a__ : Tuple = model_dic.get('size_pooling1') a__ : Optional[int] = model_dic.get('num_bp1') a__ : Tuple = model_dic.get('num_bp2') a__ : Optional[Any] = model_dic.get('num_bp3') a__ : Optional[Any] = model_dic.get('rate_weight') a__ : int = model_dic.get('rate_thre') # create model instance a__ : Union[str, Any] = CNN(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) # modify model parameter a__ : str = model_dic.get('w_conv1') a__ : Optional[int] = model_dic.get('wkj') a__ : Tuple = model_dic.get('vji') a__ : str = model_dic.get('thre_conv1') a__ : List[str] = model_dic.get('thre_bp2') a__ : Tuple = model_dic.get('thre_bp3') return conv_ins def __lowercase ( self , lowercase) -> Any: '''simple docstring''' return 1 / (1 + np.exp(-1 * x)) def __lowercase ( self , lowercase) -> Optional[int]: '''simple docstring''' return round(lowercase , 3) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase) -> Any: '''simple docstring''' a__ : Union[str, Any] = convs[0] a__ : Tuple = convs[1] a__ : Any = np.shape(lowercase)[0] # get the data slice of original image data, data_focus a__ : Tuple = [] for i_focus in range(0 , size_data - size_conv + 1 , lowercase): for j_focus in range(0 , size_data - size_conv + 1 , lowercase): a__ : str = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(lowercase) # calculate the feature map of every single kernel, and saved as list of matrix a__ : str = [] a__ : Union[str, Any] = int((size_data - size_conv) / conv_step + 1) for i_map in range(lowercase): a__ : Tuple = [] for i_focus in range(len(lowercase)): a__ : Optional[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(lowercase)) a__ : Dict = np.asmatrix(lowercase).reshape( lowercase , lowercase) data_featuremap.append(lowercase) # expanding the data slice to One dimenssion a__ : int = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(lowercase)) a__ : Optional[int] = np.asarray(lowercase) return focus_list, data_featuremap def __lowercase ( self , lowercase , lowercase , lowercase="average_pool") -> str: '''simple docstring''' a__ : Any = len(featuremaps[0]) a__ : int = int(size_map / size_pooling) a__ : Optional[Any] = [] for i_map in range(len(lowercase)): a__ : Any = featuremaps[i_map] a__ : Optional[int] = [] for i_focus in range(0 , lowercase , lowercase): for j_focus in range(0 , lowercase , lowercase): a__ : Any = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(lowercase)) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(lowercase)) a__ : List[str] = np.asmatrix(lowercase).reshape(lowercase , lowercase) featuremap_pooled.append(lowercase) return featuremap_pooled def __lowercase ( self , lowercase) -> Optional[Any]: '''simple docstring''' a__ : Any = [] for i in range(len(lowercase)): a__ : Tuple = np.shape(data[i]) a__ : List[str] = data[i].reshape(1 , shapes[0] * shapes[1]) a__ : Optional[Any] = data_listed.getA().tolist()[0] data_expanded.extend(lowercase) a__ : Union[str, Any] = np.asarray(lowercase) return data_expanded def __lowercase ( self , lowercase) -> Dict: '''simple docstring''' a__ : Dict = np.asarray(lowercase) a__ : Optional[int] = np.shape(lowercase) a__ : Any = data_mat.reshape(1 , shapes[0] * shapes[1]) return data_expanded def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase) -> str: '''simple docstring''' a__ : int = [] a__ : Optional[int] = 0 for i_map in range(lowercase): a__ : Optional[Any] = np.ones((size_map, size_map)) for i in range(0 , lowercase , lowercase): for j in range(0 , lowercase , lowercase): a__ : Union[str, Any] = pd_pool[ i_pool ] a__ : Tuple = i_pool + 1 a__ : Optional[int] = np.multiply( lowercase , np.multiply(out_map[i_map] , (1 - out_map[i_map]))) pd_all.append(lowercase) return pd_all def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase=bool) -> str: '''simple docstring''' print('----------------------Start Training-------------------------') print((' - - Shape: Train_Data ', np.shape(lowercase))) print((' - - Shape: Teach_Data ', np.shape(lowercase))) a__ : Dict = 0 a__ : List[Any] = [] a__ : Optional[int] = 1_0000 while rp < n_repeat and mse >= error_accuracy: a__ : Dict = 0 print(F'-------------Learning Time {rp}--------------') for p in range(len(lowercase)): # print('------------Learning Image: %d--------------'%p) a__ : Dict = np.asmatrix(datas_train[p]) a__ : Any = np.asarray(datas_teach[p]) a__ , a__ : Optional[int] = self.convolute( lowercase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) a__ : Dict = self.pooling(lowercase , self.size_poolinga) a__ : Optional[Any] = np.shape(lowercase) a__ : Union[str, Any] = self._expand(lowercase) a__ : List[Any] = data_bp_input a__ : Tuple = np.dot(lowercase , self.vji.T) - self.thre_bpa a__ : Any = self.sig(lowercase) a__ : Any = np.dot(lowercase , self.wkj.T) - self.thre_bpa a__ : Any = self.sig(lowercase) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- a__ : Any = np.multiply( (data_teach - bp_outa) , np.multiply(lowercase , (1 - bp_outa))) a__ : Optional[Any] = np.multiply( np.dot(lowercase , self.wkj) , np.multiply(lowercase , (1 - bp_outa))) a__ : Tuple = np.dot(lowercase , self.vji) a__ : Union[str, Any] = pd_i_all / (self.size_poolinga * self.size_poolinga) a__ : List[str] = pd_conva_pooled.T.getA().tolist() a__ : str = self._calculate_gradient_from_pool( lowercase , lowercase , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1]): a__ : Optional[int] = self._expand_mat(pd_conva_all[k_conv]) a__ : int = self.rate_weight * np.dot(lowercase , lowercase) a__ : List[str] = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0])) a__ : str = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv]) * self.rate_thre ) # all connected layer a__ : List[str] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight a__ : List[str] = self.vji + pd_j_all.T * bp_outa * self.rate_weight a__ : Tuple = self.thre_bpa - pd_k_all * self.rate_thre a__ : Tuple = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image a__ : List[str] = np.sum(abs(data_teach - bp_outa)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) a__ : Any = rp + 1 a__ : Optional[Any] = error_count / patterns all_mse.append(lowercase) def draw_error(): a__ : int = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(lowercase , '+-') plt.plot(lowercase , 'r--') plt.xlabel('Learning Times') plt.ylabel('All_mse') plt.grid(lowercase , alpha=0.5) plt.show() print('------------------Training Complished---------------------') print((' - - Training epoch: ', rp, F' - - Mse: {mse:.6f}')) if draw_e: draw_error() return mse def __lowercase ( self , lowercase) -> Optional[int]: '''simple docstring''' a__ : str = [] print('-------------------Start Testing-------------------------') print((' - - Shape: Test_Data ', np.shape(lowercase))) for p in range(len(lowercase)): a__ : int = np.asmatrix(datas_test[p]) a__ , a__ : Optional[int] = self.convolute( lowercase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) a__ : str = self.pooling(lowercase , self.size_poolinga) a__ : Optional[int] = self._expand(lowercase) a__ : str = data_bp_input a__ : Union[str, Any] = bp_outa * self.vji.T - self.thre_bpa a__ : Optional[Any] = self.sig(lowercase) a__ : int = bp_outa * self.wkj.T - self.thre_bpa a__ : Dict = self.sig(lowercase) produce_out.extend(bp_outa.getA().tolist()) a__ : List[Any] = [list(map(self.do_round , lowercase)) for each in produce_out] return np.asarray(lowercase) def __lowercase ( self , lowercase) -> str: '''simple docstring''' a__ : str = np.asmatrix(lowercase) a__ , a__ : str = self.convolute( lowercase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) a__ : List[str] = self.pooling(lowercase , self.size_poolinga) return data_conveda, data_pooleda if __name__ == "__main__": pass
225
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class _UpperCAmelCase( metaclass=lowerCamelCase ): lowercase__ = ['note_seq'] def __init__( self , *__a , **__a) -> Dict: '''simple docstring''' requires_backends(self , ['''note_seq''']) @classmethod def UpperCAmelCase ( cls , *__a , **__a) -> Dict: '''simple docstring''' requires_backends(cls , ['''note_seq''']) @classmethod def UpperCAmelCase ( cls , *__a , **__a) -> Tuple: '''simple docstring''' requires_backends(cls , ['''note_seq'''])
194
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int: """simple docstring""" if isinstance(__snake_case, torch.Tensor ): return image elif isinstance(__snake_case, PIL.Image.Image ): _UpperCamelCase = [image] if isinstance(image[0], PIL.Image.Image ): _UpperCamelCase = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] _UpperCamelCase = np.concatenate(__snake_case, axis=0 ) _UpperCamelCase = np.array(__snake_case ).astype(np.floataa ) / 255.0 _UpperCamelCase = image.transpose(0, 3, 1, 2 ) _UpperCamelCase = 2.0 * image - 1.0 _UpperCamelCase = torch.from_numpy(__snake_case ) elif isinstance(image[0], torch.Tensor ): _UpperCamelCase = torch.cat(__snake_case, dim=0 ) return image def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=0.9995 ) -> List[Any]: """simple docstring""" if not isinstance(__snake_case, np.ndarray ): _UpperCamelCase = True _UpperCamelCase = va.device _UpperCamelCase = va.cpu().numpy() _UpperCamelCase = va.cpu().numpy() _UpperCamelCase = np.sum(va * va / (np.linalg.norm(__snake_case ) * np.linalg.norm(__snake_case )) ) if np.abs(__snake_case ) > DOT_THRESHOLD: _UpperCamelCase = (1 - t) * va + t * va else: _UpperCamelCase = np.arccos(__snake_case ) _UpperCamelCase = np.sin(__snake_case ) _UpperCamelCase = theta_a * t _UpperCamelCase = np.sin(__snake_case ) _UpperCamelCase = np.sin(theta_a - theta_t ) / sin_theta_a _UpperCamelCase = sin_theta_t / sin_theta_a _UpperCamelCase = sa * va + sa * va if inputs_are_torch: _UpperCamelCase = torch.from_numpy(__snake_case ).to(__snake_case ) return va def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]: """simple docstring""" _UpperCamelCase = F.normalize(__snake_case, dim=-1 ) _UpperCamelCase = F.normalize(__snake_case, dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]: """simple docstring""" for param in model.parameters(): _UpperCamelCase = value class _UpperCAmelCase( lowerCamelCase ): def __init__( self , __a , __a , __a , __a , __a , __a , __a , __a=None , __a=None , __a=None , ) -> List[str]: '''simple docstring''' super().__init__() self.register_modules( vae=__a , text_encoder=__a , clip_model=__a , tokenizer=__a , unet=__a , scheduler=__a , feature_extractor=__a , coca_model=__a , coca_tokenizer=__a , coca_transform=__a , ) _UpperCamelCase = ( feature_extractor.size if isinstance(feature_extractor.size , __a) else feature_extractor.size['''shortest_edge'''] ) _UpperCamelCase = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std) set_requires_grad(self.text_encoder , __a) set_requires_grad(self.clip_model , __a) def UpperCAmelCase ( self , __a = "auto") -> Union[str, Any]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _UpperCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a) def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' self.enable_attention_slicing(__a) def UpperCAmelCase ( self) -> int: '''simple docstring''' set_requires_grad(self.vae , __a) def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' set_requires_grad(self.vae , __a) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' set_requires_grad(self.unet , __a) def UpperCAmelCase ( self) -> int: '''simple docstring''' set_requires_grad(self.unet , __a) def UpperCAmelCase ( self , __a , __a , __a) -> Any: '''simple docstring''' # get the original timestep using init_timestep _UpperCamelCase = min(int(num_inference_steps * strength) , __a) _UpperCamelCase = max(num_inference_steps - init_timestep , 0) _UpperCamelCase = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a=None) -> Tuple: '''simple docstring''' if not isinstance(__a , torch.Tensor): raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(__a)}''') _UpperCamelCase = image.to(device=__a , dtype=__a) if isinstance(__a , __a): _UpperCamelCase = [ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(__a) ] _UpperCamelCase = torch.cat(__a , dim=0) else: _UpperCamelCase = self.vae.encode(__a).latent_dist.sample(__a) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCamelCase = 0.1_8215 * init_latents _UpperCamelCase = init_latents.repeat_interleave(__a , dim=0) _UpperCamelCase = randn_tensor(init_latents.shape , generator=__a , device=__a , dtype=__a) # get latents _UpperCamelCase = self.scheduler.add_noise(__a , __a , __a) _UpperCamelCase = init_latents return latents def UpperCAmelCase ( self , __a) -> str: '''simple docstring''' _UpperCamelCase = self.coca_transform(__a).unsqueeze(0) with torch.no_grad(), torch.cuda.amp.autocast(): _UpperCamelCase = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype)) _UpperCamelCase = self.coca_tokenizer.decode(generated[0].cpu().numpy()) return generated.split('''<end_of_text>''')[0].replace('''<start_of_text>''' , '''''').rstrip(''' .,''') def UpperCAmelCase ( self , __a , __a) -> Optional[int]: '''simple docstring''' _UpperCamelCase = self.feature_extractor.preprocess(__a) _UpperCamelCase = torch.from_numpy(clip_image_input['''pixel_values'''][0]).unsqueeze(0).to(self.device).half() _UpperCamelCase = self.clip_model.get_image_features(__a) _UpperCamelCase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__a) _UpperCamelCase = image_embeddings_clip.repeat_interleave(__a , dim=0) return image_embeddings_clip @torch.enable_grad() def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a , ) -> Tuple: '''simple docstring''' _UpperCamelCase = latents.detach().requires_grad_() _UpperCamelCase = self.scheduler.scale_model_input(__a , __a) # predict the noise residual _UpperCamelCase = self.unet(__a , __a , encoder_hidden_states=__a).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)): _UpperCamelCase = self.scheduler.alphas_cumprod[timestep] _UpperCamelCase = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _UpperCamelCase = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 _UpperCamelCase = torch.sqrt(__a) _UpperCamelCase = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __a): _UpperCamelCase = self.scheduler.sigmas[index] _UpperCamelCase = latents - sigma * noise_pred else: raise ValueError(F'''scheduler type {type(self.scheduler)} not supported''') # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCamelCase = 1 / 0.1_8215 * sample _UpperCamelCase = self.vae.decode(__a).sample _UpperCamelCase = (image / 2 + 0.5).clamp(0 , 1) _UpperCamelCase = transforms.Resize(self.feature_extractor_size)(__a) _UpperCamelCase = self.normalize(__a).to(latents.dtype) _UpperCamelCase = self.clip_model.get_image_features(__a) _UpperCamelCase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__a) _UpperCamelCase = spherical_dist_loss(__a , __a).mean() * clip_guidance_scale _UpperCamelCase = -torch.autograd.grad(__a , __a)[0] if isinstance(self.scheduler , __a): _UpperCamelCase = latents.detach() + grads * (sigma**2) _UpperCamelCase = noise_pred_original else: _UpperCamelCase = noise_pred_original - torch.sqrt(__a) * grads return noise_pred, latents @torch.no_grad() def __call__( self , __a , __a , __a = None , __a = None , __a = 5_12 , __a = 5_12 , __a = 0.6 , __a = 50 , __a = 7.5 , __a = 1 , __a = 0.0 , __a = 1_00 , __a = None , __a = "pil" , __a = True , __a = 0.8 , __a = 0.1 , __a = 0.1 , ) -> Dict: '''simple docstring''' if isinstance(__a , __a) and len(__a) != batch_size: raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(__a)} generators.''') if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''') if isinstance(__a , torch.Generator) and batch_size > 1: _UpperCamelCase = [generator] + [None] * (batch_size - 1) _UpperCamelCase = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] _UpperCamelCase = [x[0] for x in coca_is_none if x[1]] _UpperCamelCase = ''', '''.join(__a) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__a): raise ValueError( F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''') _UpperCamelCase = self.get_image_description(__a) if style_prompt is None: if len(__a): raise ValueError( F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''') _UpperCamelCase = self.get_image_description(__a) # get prompt text embeddings for content and style _UpperCamelCase = self.tokenizer( __a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , ) _UpperCamelCase = self.text_encoder(content_text_input.input_ids.to(self.device))[0] _UpperCamelCase = self.tokenizer( __a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , ) _UpperCamelCase = self.text_encoder(style_text_input.input_ids.to(self.device))[0] _UpperCamelCase = slerp(__a , __a , __a) # duplicate text embeddings for each generation per prompt _UpperCamelCase = text_embeddings.repeat_interleave(__a , dim=0) # set timesteps _UpperCamelCase = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys()) _UpperCamelCase = {} if accepts_offset: _UpperCamelCase = 1 self.scheduler.set_timesteps(__a , **__a) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device) _UpperCamelCase , _UpperCamelCase = self.get_timesteps(__a , __a , self.device) _UpperCamelCase = timesteps[:1].repeat(__a) # Preprocess image _UpperCamelCase = preprocess(__a , __a , __a) _UpperCamelCase = self.prepare_latents( __a , __a , __a , text_embeddings.dtype , self.device , __a) _UpperCamelCase = preprocess(__a , __a , __a) _UpperCamelCase = self.prepare_latents( __a , __a , __a , text_embeddings.dtype , self.device , __a) _UpperCamelCase = slerp(__a , __a , __a) if clip_guidance_scale > 0: _UpperCamelCase = self.get_clip_image_embeddings(__a , __a) _UpperCamelCase = self.get_clip_image_embeddings(__a , __a) _UpperCamelCase = slerp( __a , __a , __a) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _UpperCamelCase = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _UpperCamelCase = content_text_input.input_ids.shape[-1] _UpperCamelCase = self.tokenizer([''''''] , padding='''max_length''' , max_length=__a , return_tensors='''pt''') _UpperCamelCase = self.text_encoder(uncond_input.input_ids.to(self.device))[0] # duplicate unconditional embeddings for each generation per prompt _UpperCamelCase = uncond_embeddings.repeat_interleave(__a , dim=0) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _UpperCamelCase = torch.cat([uncond_embeddings, text_embeddings]) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _UpperCamelCase = (batch_size, self.unet.config.in_channels, height // 8, width // 8) _UpperCamelCase = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps _UpperCamelCase = torch.randn(__a , generator=__a , device='''cpu''' , dtype=__a).to( self.device) else: _UpperCamelCase = torch.randn(__a , generator=__a , device=self.device , dtype=__a) else: if latents.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''') _UpperCamelCase = latents.to(self.device) # scale the initial noise by the standard deviation required by the scheduler _UpperCamelCase = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _UpperCamelCase = '''eta''' in set(inspect.signature(self.scheduler.step).parameters.keys()) _UpperCamelCase = {} if accepts_eta: _UpperCamelCase = eta # check if the scheduler accepts generator _UpperCamelCase = '''generator''' in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: _UpperCamelCase = generator with self.progress_bar(total=__a): for i, t in enumerate(__a): # expand the latents if we are doing classifier free guidance _UpperCamelCase = torch.cat([latents] * 2) if do_classifier_free_guidance else latents _UpperCamelCase = self.scheduler.scale_model_input(__a , __a) # predict the noise residual _UpperCamelCase = self.unet(__a , __a , encoder_hidden_states=__a).sample # perform classifier free guidance if do_classifier_free_guidance: _UpperCamelCase , _UpperCamelCase = noise_pred.chunk(2) _UpperCamelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: _UpperCamelCase = ( text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings ) _UpperCamelCase , _UpperCamelCase = self.cond_fn( __a , __a , __a , __a , __a , __a , __a , ) # compute the previous noisy sample x_t -> x_t-1 _UpperCamelCase = self.scheduler.step(__a , __a , __a , **__a).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCamelCase = 1 / 0.1_8215 * latents _UpperCamelCase = self.vae.decode(__a).sample _UpperCamelCase = (image / 2 + 0.5).clamp(0 , 1) _UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": _UpperCamelCase = self.numpy_to_pil(__a) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__a , nsfw_content_detected=__a)
194
1
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class A ( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = VideoToVideoSDPipeline lowerCamelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'} ) - {'image', 'width', 'height'} lowerCamelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'} ) - {'image'} lowerCamelCase = PipelineTesterMixin.required_optional_params - {'latents'} lowerCamelCase = False # No `output_type`. lowerCamelCase = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'return_dict', 'callback', 'callback_steps', ] ) def snake_case__ ( self : Tuple )-> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) A__ = UNetaDConditionModel( block_out_channels=(3_2, 6_4, 6_4, 6_4),layers_per_block=2,sample_size=3_2,in_channels=4,out_channels=4,down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D'),up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D'),cross_attention_dim=3_2,attention_head_dim=4,) A__ = DDIMScheduler( beta_start=0.00_085,beta_end=0.012,beta_schedule='scaled_linear',clip_sample=lowercase_,set_alpha_to_one=lowercase_,) torch.manual_seed(0 ) A__ = AutoencoderKL( block_out_channels=[3_2, 6_4],in_channels=3,out_channels=3,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'],up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'],latent_channels=4,sample_size=1_2_8,) torch.manual_seed(0 ) A__ = CLIPTextConfig( bos_token_id=0,eos_token_id=2,hidden_size=3_2,intermediate_size=3_7,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1_0_0_0,hidden_act='gelu',projection_dim=5_1_2,) A__ = CLIPTextModel(lowercase_ ) A__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) A__ = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def snake_case__ ( self : Optional[Any],lowercase_ : Optional[int],lowercase_ : List[Any]=0 )-> Any: '''simple docstring''' A__ = floats_tensor((1, 3, 3, 3_2, 3_2),rng=random.Random(lowercase_ ) ).to(lowercase_ ) if str(lowercase_ ).startswith('mps' ): A__ = torch.manual_seed(lowercase_ ) else: A__ = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) A__ = { 'prompt': 'A painting of a squirrel eating a burger', 'video': video, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def snake_case__ ( self : List[Any] )-> List[Any]: '''simple docstring''' A__ = 'cpu' # ensure determinism for the device-dependent torch.Generator A__ = self.get_dummy_components() A__ = VideoToVideoSDPipeline(**lowercase_ ) A__ = sd_pipe.to(lowercase_ ) sd_pipe.set_progress_bar_config(disable=lowercase_ ) A__ = self.get_dummy_inputs(lowercase_ ) A__ = 'np' A__ = sd_pipe(**lowercase_ ).frames A__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (3_2, 3_2, 3) A__ = np.array([1_0_6, 1_1_7, 1_1_3, 1_7_4, 1_3_7, 1_1_2, 1_4_8, 1_5_1, 1_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available(),reason='XFormers attention is only available with CUDA and `xformers` installed',) def snake_case__ ( self : Optional[Any] )-> int: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowercase_,expected_max_diff=5E-3 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def snake_case__ ( self : Any )-> Optional[int]: '''simple docstring''' pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def snake_case__ ( self : int )-> int: '''simple docstring''' pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def snake_case__ ( self : List[Any] )-> List[str]: '''simple docstring''' pass def snake_case__ ( self : Optional[int] )-> Optional[Any]: '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class A ( unittest.TestCase ): """simple docstring""" def snake_case__ ( self : List[str] )-> Dict: '''simple docstring''' A__ = VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL',torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames A__ = torch.Generator(device='cpu' ).manual_seed(0 ) A__ = torch.randn((1, 1_0, 3, 1_0_2_4, 5_7_6),generator=lowercase_ ) A__ = video.to('cuda' ) A__ = 'Spiderman is surfing' A__ = pipe(lowercase_,video=lowercase_,generator=lowercase_,num_inference_steps=3,output_type='pt' ).frames A__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
282
from __future__ import annotations from scipy.special import comb # type: ignore class A : """simple docstring""" def __init__( self : Any,lowercase_ : list[tuple[float, float]] )-> Optional[int]: '''simple docstring''' A__ = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. A__ = len(lowercase_ ) - 1 def snake_case__ ( self : List[Any],lowercase_ : float )-> list[float]: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." A__ = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree,lowercase_ ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(lowercase_ ),5 ) == 1 return output_values def snake_case__ ( self : str,lowercase_ : float )-> tuple[float, float]: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." A__ = self.basis_function(lowercase_ ) A__ = 0.0 A__ = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def snake_case__ ( self : str,lowercase_ : float = 0.01 )-> str: '''simple docstring''' from matplotlib import pyplot as plt # type: ignore A__ = [] # x coordinates of points to plot A__ = [] # y coordinates of points to plot A__ = 0.0 while t <= 1: A__ = self.bezier_curve_function(lowercase_ ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size A__ = [i[0] for i in self.list_of_points] A__ = [i[1] for i in self.list_of_points] plt.plot( lowercase_,lowercase_,color='blue',label='Curve of Degree ' + str(self.degree ),) plt.scatter(lowercase_,lowercase_,color='red',label='Control Points' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
282
1
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class snake_case_: def __init__( self : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[int]=sys.maxsize ): lowerCAmelCase : Optional[Any] = "bilinear" lowerCAmelCase : Dict = max_size lowerCAmelCase : List[Any] = short_edge_length def __call__( self : Any , UpperCamelCase_ : int ): lowerCAmelCase : Any = [] for img in imgs: lowerCAmelCase : int = img.shape[:2] # later: provide list and randomly choose index for resize lowerCAmelCase : Tuple = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img lowerCAmelCase : List[Any] = size * 1.0 / min(UpperCamelCase__ , UpperCamelCase__ ) if h < w: lowerCAmelCase : Tuple = size, scale * w else: lowerCAmelCase : str = scale * h, size if max(UpperCamelCase__ , UpperCamelCase__ ) > self.max_size: lowerCAmelCase : Union[str, Any] = self.max_size * 1.0 / max(UpperCamelCase__ , UpperCamelCase__ ) lowerCAmelCase : Optional[int] = newh * scale lowerCAmelCase : str = neww * scale lowerCAmelCase : Union[str, Any] = int(neww + 0.5 ) lowerCAmelCase : int = int(newh + 0.5 ) if img.dtype == np.uinta: lowerCAmelCase : List[Any] = Image.fromarray(UpperCamelCase__ ) lowerCAmelCase : str = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) lowerCAmelCase : List[Any] = np.asarray(UpperCamelCase__ ) else: lowerCAmelCase : int = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw lowerCAmelCase : Tuple = nn.functional.interpolate( UpperCamelCase__ , (newh, neww) , mode=self.interp_method , align_corners=UpperCamelCase__ ).squeeze(0 ) img_augs.append(UpperCamelCase__ ) return img_augs class snake_case_: def __init__( self : int , UpperCamelCase_ : List[str] ): lowerCAmelCase : Tuple = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) lowerCAmelCase : Optional[int] = cfg.INPUT.FORMAT lowerCAmelCase : Union[str, Any] = cfg.SIZE_DIVISIBILITY lowerCAmelCase : Dict = cfg.PAD_VALUE lowerCAmelCase : List[str] = cfg.INPUT.MAX_SIZE_TEST lowerCAmelCase : List[Any] = cfg.MODEL.DEVICE lowerCAmelCase : Any = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowerCAmelCase : Dict = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowerCAmelCase : Union[str, Any] = lambda UpperCamelCase_ : (x - self.pixel_mean) / self.pixel_std def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Optional[Any] ): lowerCAmelCase : str = tuple(max(UpperCamelCase__ ) for s in zip(*[img.shape for img in images] ) ) lowerCAmelCase : Optional[Any] = [im.shape[-2:] for im in images] lowerCAmelCase : Optional[Any] = [ nn.functional.pad( UpperCamelCase__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(UpperCamelCase__ , UpperCamelCase__ ) ] return torch.stack(UpperCamelCase__ ), torch.tensor(UpperCamelCase__ ) def __call__( self : Any , UpperCamelCase_ : Dict , UpperCamelCase_ : int=False ): with torch.no_grad(): if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCAmelCase : List[Any] = [images] if single_image: assert len(UpperCamelCase__ ) == 1 for i in range(len(UpperCamelCase__ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(UpperCamelCase__ , images.pop(UpperCamelCase__ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( UpperCamelCase__ , torch.as_tensor(img_tensorize(images.pop(UpperCamelCase__ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge lowerCAmelCase : Tuple = torch.tensor([im.shape[:2] for im in images] ) lowerCAmelCase : Optional[int] = self.aug(UpperCamelCase__ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic lowerCAmelCase : Optional[Any] = [self.normalizer(UpperCamelCase__ ) for x in images] # now pad them to do the following operations lowerCAmelCase : List[str] = self.pad(UpperCamelCase__ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad lowerCAmelCase : str = torch.true_divide(UpperCamelCase__ , UpperCamelCase__ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _snake_case ( _snake_case : Optional[int] , _snake_case : Union[str, Any] ): boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _snake_case ( _snake_case : Dict , _snake_case : Tuple ): assert torch.isfinite(__SCREAMING_SNAKE_CASE ).all(), "Box tensor contains infinite or NaN!" lowerCAmelCase : str = box_size tensor[:, 0].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE ) tensor[:, 1].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE ) tensor[:, 2].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE ) tensor[:, 3].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE )
60
"""simple docstring""" import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( __snake_case, unittest.TestCase ): SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : Tuple = BloomTokenizerFast SCREAMING_SNAKE_CASE_ : str = BloomTokenizerFast SCREAMING_SNAKE_CASE_ : int = True SCREAMING_SNAKE_CASE_ : Tuple = False SCREAMING_SNAKE_CASE_ : int = """tokenizer_file""" SCREAMING_SNAKE_CASE_ : List[str] = {"""bos_token""": """<s>""", """eos_token""": """</s>""", """unk_token""": """<unk>""", """pad_token""": """<pad>"""} def lowercase_ ( self : List[Any])-> Dict: '''simple docstring''' super().setUp() __lowerCAmelCase: Optional[Any] = BloomTokenizerFast.from_pretrained("bigscience/tokenizer") tokenizer.save_pretrained(self.tmpdirname) def lowercase_ ( self : List[Any] , **UpperCamelCase__ : Union[str, Any])-> Optional[Any]: '''simple docstring''' kwargs.update(self.special_tokens_map) return BloomTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__) def lowercase_ ( self : Union[str, Any])-> Union[str, Any]: '''simple docstring''' __lowerCAmelCase: str = self.get_rust_tokenizer() __lowerCAmelCase: int = ["The quick brown fox</s>", "jumps over the lazy dog</s>"] __lowerCAmelCase: List[str] = [[2_1_7_5, 2_3_7_1_4, 7_3_1_7_3, 1_4_4_2_5_2, 2], [7_7, 1_3_2_6_1_9, 3_4_7_8, 3_6_8, 1_0_9_5_8_6, 3_5_4_3_3, 2]] __lowerCAmelCase: List[str] = tokenizer.batch_encode_plus(UpperCamelCase__)["input_ids"] self.assertListEqual(UpperCamelCase__ , UpperCamelCase__) __lowerCAmelCase: List[Any] = tokenizer.batch_decode(UpperCamelCase__) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__) def lowercase_ ( self : Optional[Any] , UpperCamelCase__ : Tuple=6)-> Tuple: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): __lowerCAmelCase: Optional[Any] = self.rust_tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input __lowerCAmelCase: Dict = "This is a simple input" __lowerCAmelCase: str = ["This is a simple input 1", "This is a simple input 2"] __lowerCAmelCase: int = ("This is a simple input", "This is a pair") __lowerCAmelCase: Union[str, Any] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests try: tokenizer_r.encode(UpperCamelCase__ , max_length=UpperCamelCase__) tokenizer_r.encode_plus(UpperCamelCase__ , max_length=UpperCamelCase__) tokenizer_r.batch_encode_plus(UpperCamelCase__ , max_length=UpperCamelCase__) tokenizer_r.encode(UpperCamelCase__ , max_length=UpperCamelCase__) tokenizer_r.batch_encode_plus(UpperCamelCase__ , max_length=UpperCamelCase__) except ValueError: self.fail("Bloom Tokenizer should be able to deal with padding") __lowerCAmelCase: Tuple = None # Hotfixing padding = None self.assertRaises(UpperCamelCase__ , tokenizer_r.encode , UpperCamelCase__ , max_length=UpperCamelCase__ , padding="max_length") # Simple input self.assertRaises(UpperCamelCase__ , tokenizer_r.encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding="max_length") # Simple input self.assertRaises( UpperCamelCase__ , tokenizer_r.batch_encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding="max_length" , ) # Pair input self.assertRaises(UpperCamelCase__ , tokenizer_r.encode , UpperCamelCase__ , max_length=UpperCamelCase__ , padding="max_length") # Pair input self.assertRaises(UpperCamelCase__ , tokenizer_r.encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding="max_length") # Pair input self.assertRaises( UpperCamelCase__ , tokenizer_r.batch_encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding="max_length" , ) def lowercase_ ( self : Optional[Any])-> List[str]: '''simple docstring''' __lowerCAmelCase: Dict = self.get_rust_tokenizer() __lowerCAmelCase: List[str] = load_dataset("xnli" , "all_languages" , split="test" , streaming=UpperCamelCase__) __lowerCAmelCase: Union[str, Any] = next(iter(UpperCamelCase__))["premise"] # pick up one data __lowerCAmelCase: Any = list(sample_data.values()) __lowerCAmelCase: int = list(map(tokenizer.encode , UpperCamelCase__)) __lowerCAmelCase: str = [tokenizer.decode(UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__) for x in output_tokens] self.assertListEqual(UpperCamelCase__ , UpperCamelCase__) def lowercase_ ( self : Optional[int])-> str: '''simple docstring''' self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map) , 1) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values())[0]) , 1)
217
0
"""simple docstring""" def _UpperCAmelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : List[str] ) -> Optional[Any]: _snake_case = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _UpperCAmelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : List[Any] ) -> Optional[int]: _snake_case = 0 while b > 0: if b & 1: _snake_case = ((res % c) + (a % c)) % c a += a b >>= 1 return res
40
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
40
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : List[str] = logging.get_logger(__name__) __lowercase : Any = { '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''', # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class __lowercase ( _lowercase ): lowerCamelCase : List[Any] = "pegasus" lowerCamelCase : Union[str, Any] = ["past_key_values"] lowerCamelCase : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__(self , A=5_0_2_6_5 , A=1_0_2_4 , A=1_2 , A=4_0_9_6 , A=1_6 , A=1_2 , A=4_0_9_6 , A=1_6 , A=0.0 , A=0.0 , A=True , A=True , A="gelu" , A=1_0_2_4 , A=0.1 , A=0.0 , A=0.0 , A=0.02 , A=0 , A=False , A=0 , A=1 , A=1 , **A , ): lowerCamelCase_ : Tuple = vocab_size lowerCamelCase_ : Union[str, Any] = max_position_embeddings lowerCamelCase_ : Union[str, Any] = d_model lowerCamelCase_ : Any = encoder_ffn_dim lowerCamelCase_ : int = encoder_layers lowerCamelCase_ : Optional[int] = encoder_attention_heads lowerCamelCase_ : Union[str, Any] = decoder_ffn_dim lowerCamelCase_ : Optional[int] = decoder_layers lowerCamelCase_ : Dict = decoder_attention_heads lowerCamelCase_ : Optional[Any] = dropout lowerCamelCase_ : Any = attention_dropout lowerCamelCase_ : Dict = activation_dropout lowerCamelCase_ : Optional[int] = activation_function lowerCamelCase_ : Any = init_std lowerCamelCase_ : Dict = encoder_layerdrop lowerCamelCase_ : Union[str, Any] = decoder_layerdrop lowerCamelCase_ : int = use_cache lowerCamelCase_ : Dict = encoder_layers lowerCamelCase_ : int = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=A , eos_token_id=A , is_encoder_decoder=A , decoder_start_token_id=A , forced_eos_token_id=A , **A , ) @property def UpperCAmelCase__ (self ): return self.encoder_attention_heads @property def UpperCAmelCase__ (self ): return self.d_model
318
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : str = logging.get_logger(__name__) __lowercase : Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __lowercase ( _lowercase ): lowerCamelCase : int = "ctrl" lowerCamelCase : Optional[int] = ["past_key_values"] lowerCamelCase : Optional[int] = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__(self , A=2_4_6_5_3_4 , A=2_5_6 , A=1_2_8_0 , A=8_1_9_2 , A=4_8 , A=1_6 , A=0.1 , A=0.1 , A=1E-6 , A=0.02 , A=True , **A , ): lowerCamelCase_ : List[str] = vocab_size lowerCamelCase_ : Optional[Any] = n_positions lowerCamelCase_ : List[Any] = n_embd lowerCamelCase_ : Optional[Any] = n_layer lowerCamelCase_ : Any = n_head lowerCamelCase_ : int = dff lowerCamelCase_ : str = resid_pdrop lowerCamelCase_ : List[Any] = embd_pdrop lowerCamelCase_ : List[Any] = layer_norm_epsilon lowerCamelCase_ : Any = initializer_range lowerCamelCase_ : Dict = use_cache super().__init__(**A )
318
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __SCREAMING_SNAKE_CASE ={"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE =[ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
370
"""simple docstring""" from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
321
0
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split UpperCAmelCase_ : Optional[int] = datasets.load_iris() UpperCAmelCase_ : int = np.array(data['data']) UpperCAmelCase_ : Optional[int] = np.array(data['target']) UpperCAmelCase_ : Tuple = data['target_names'] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Tuple = train_test_split(X, y) def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] , __A : str ) -> str: """simple docstring""" return np.linalg.norm(np.array(__A ) - np.array(__A ) ) def SCREAMING_SNAKE_CASE_ ( __A : Optional[Any] , __A : Optional[Any] , __A : Union[str, Any] , __A : Tuple , __A : Any=5 ) -> str: """simple docstring""" a_ : str = zip(__A , __A ) # List of distances of all points from the point to be classified a_ : Tuple = [] for data_point in data: a_ : int = euclidean_distance(data_point[0] , __A ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. a_ : Tuple = [i[1] for i in sorted(__A )[:k]] # Most commonly occurring class among them # is the class into which the point is classified a_ : Tuple = Counter(__A ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
32
'''simple docstring''' import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class lowerCAmelCase_: '''simple docstring''' def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Optional[Any]: return None class lowerCAmelCase_: '''simple docstring''' def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Tuple: return None class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' __lowercase : Dict = [ # (model_name, model_kwargs) ('''bert-base-cased''', {}), ('''gpt2''', {'''use_cache''': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase_ ( self ) -> int: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__UpperCAmelCase ,"""tf""" ,12 ,**__UpperCAmelCase ) @require_torch @slow def UpperCAmelCase_ ( self ) -> Union[str, Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__UpperCAmelCase ,"""pt""" ,12 ,**__UpperCAmelCase ) @require_torch @slow def UpperCAmelCase_ ( self ) -> Any: from transformers import BertModel lowerCAmelCase__ : Optional[int] = ["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""] with NamedTemporaryFile(mode="""w+t""" ) as vocab_file: vocab_file.write("""\n""".join(__UpperCAmelCase ) ) vocab_file.flush() lowerCAmelCase__ : Dict = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: lowerCAmelCase__ : Tuple = BertModel(BertConfig(vocab_size=len(__UpperCAmelCase ) ) ) model.save_pretrained(__UpperCAmelCase ) self._test_export(__UpperCAmelCase ,"""pt""" ,12 ,__UpperCAmelCase ) @require_tf @slow def UpperCAmelCase_ ( self ) -> List[str]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowerCAmelCase__ : Dict = self._test_export(__UpperCAmelCase ,"""tf""" ,12 ,**__UpperCAmelCase ) lowerCAmelCase__ : List[str] = quantize(Path(__UpperCAmelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__UpperCAmelCase ).stat().st_size: self.fail("""Quantized model is bigger than initial ONNX model""" ) @require_torch @slow def UpperCAmelCase_ ( self ) -> List[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowerCAmelCase__ : Any = self._test_export(__UpperCAmelCase ,"""pt""" ,12 ,**__UpperCAmelCase ) lowerCAmelCase__ : Dict = quantize(__UpperCAmelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__UpperCAmelCase ).stat().st_size: self.fail("""Quantized model is bigger than initial ONNX model""" ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase=None ,**__UpperCAmelCase ) -> Optional[Any]: try: # Compute path with TemporaryDirectory() as tempdir: lowerCAmelCase__ : Optional[int] = Path(__UpperCAmelCase ).joinpath("""model.onnx""" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,**__UpperCAmelCase ) return path except Exception as e: self.fail(__UpperCAmelCase ) @require_torch @require_tokenizers @slow def UpperCAmelCase_ ( self ) -> Union[str, Any]: from transformers import BertModel lowerCAmelCase__ : List[Any] = BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) ) lowerCAmelCase__ : Union[str, Any] = BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" ) self._test_infer_dynamic_axis(__UpperCAmelCase ,__UpperCAmelCase ,"""pt""" ) @require_tf @require_tokenizers @slow def UpperCAmelCase_ ( self ) -> Optional[int]: from transformers import TFBertModel lowerCAmelCase__ : int = TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) ) lowerCAmelCase__ : Optional[int] = BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" ) self._test_infer_dynamic_axis(__UpperCAmelCase ,__UpperCAmelCase ,"""tf""" ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Tuple: lowerCAmelCase__ : Any = FeatureExtractionPipeline(__UpperCAmelCase ,__UpperCAmelCase ) lowerCAmelCase__ : List[str] = ["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = infer_shapes(__UpperCAmelCase ,__UpperCAmelCase ) # Assert all variables are present self.assertEqual(len(__UpperCAmelCase ) ,len(__UpperCAmelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] ,__UpperCAmelCase ) self.assertSequenceEqual(variable_names[3:] ,__UpperCAmelCase ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] ,{0: """batch""", 1: """sequence"""} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["""output_0"""] ,{0: """batch""", 1: """sequence"""} ) self.assertDictEqual(shapes["""output_1"""] ,{0: """batch"""} ) def UpperCAmelCase_ ( self ) -> Optional[int]: lowerCAmelCase__ : List[str] = ["""input_ids""", """attention_mask""", """token_type_ids"""] lowerCAmelCase__ : Union[str, Any] = {"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]} lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = ensure_valid_input(FuncContiguousArgs() ,__UpperCAmelCase ,__UpperCAmelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__UpperCAmelCase ) ,3 ) # Should have exactly the same input names self.assertEqual(set(__UpperCAmelCase ) ,set(__UpperCAmelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__UpperCAmelCase ,(tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) lowerCAmelCase__ , lowerCAmelCase__ : int = ensure_valid_input(FuncNonContiguousArgs() ,__UpperCAmelCase ,__UpperCAmelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__UpperCAmelCase ) ,1 ) self.assertEqual(len(__UpperCAmelCase ) ,1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] ,tokens["""input_ids"""] ) self.assertEqual(ordered_input_names[0] ,"""input_ids""" ) def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : Dict = generate_identified_filename(Path("""/home/something/my_fake_model.onnx""" ) ,"""-test""" ) self.assertEqual("""/home/something/my_fake_model-test.onnx""" ,generated.as_posix() )
37
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=__lowerCAmelCase ) class lowerCamelCase_ ( __lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = field(default='automatic-speech-recognition' , metadata={'include_in_asdict_even_if_is_default': True} ) SCREAMING_SNAKE_CASE_ = Features({'audio': Audio()} ) SCREAMING_SNAKE_CASE_ = Features({'transcription': Value('string' )} ) SCREAMING_SNAKE_CASE_ = "audio" SCREAMING_SNAKE_CASE_ = "transcription" def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : Dict ): '''simple docstring''' if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] ,lowerCamelCase__ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) a = copy.deepcopy(self ) a = self.input_schema.copy() a = features[self.audio_column] a = input_schema return task_template @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' return {self.audio_column: "audio", self.transcription_column: "transcription"}
357
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = 0.01 with locka.acquire(): with pytest.raises(snake_case_ ): a = time.time() locka.acquire(snake_case_ ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = '''a''' * 1_0_0_0 + '''.lock''' a = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('''.lock''' ) assert not locka._lock_file.endswith(snake_case_ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 a = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case_ ): locka.acquire(0 )
330
0
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def lowerCAmelCase_ ( snake_case_ : Dict ) ->Tuple: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def lowerCAmelCase_ ( ) ->Any: with parallel_backend('spark' ): assert ParallelBackendConfig.backend_name == "spark" lowerCamelCase__ : Tuple =[1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend('unsupported backend' ): map_nested(snake_case_ , snake_case_ , num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend('unsupported backend' ): map_nested(snake_case_ , snake_case_ , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('num_proc' , [2, -1] ) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) ->Any: lowerCamelCase__ : Union[str, Any] =[1, 2] lowerCamelCase__ : str ={'a': 1, 'b': 2} lowerCamelCase__ : Union[str, Any] ={'a': [1, 2], 'b': [3, 4]} lowerCamelCase__ : Optional[int] ={'a': {'1': 1}, 'b': 2} lowerCamelCase__ : List[Any] ={'a': 1, 'b': 2, 'c': 3, 'd': 4} lowerCamelCase__ : str =[2, 3] lowerCamelCase__ : Optional[Any] ={'a': 2, 'b': 3} lowerCamelCase__ : int ={'a': [2, 3], 'b': [4, 5]} lowerCamelCase__ : Any ={'a': {'1': 2}, 'b': 3} lowerCamelCase__ : Any ={'a': 2, 'b': 3, 'c': 4, 'd': 5} with parallel_backend('spark' ): assert map_nested(snake_case_ , snake_case_ , num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ , snake_case_ , num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ , snake_case_ , num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ , snake_case_ , num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ , snake_case_ , num_proc=snake_case_ ) == expected_map_nested_sa
126
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowerCAmelCase = logging.get_logger(__name__) class A_ ( A__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ["""audio_values""", """audio_mask"""] def __init__( self :List[str] , lowerCamelCase_ :List[str]=2_048 , lowerCamelCase_ :Dict=1 , lowerCamelCase_ :int=[16, 16] , lowerCamelCase_ :str=128 , lowerCamelCase_ :Union[str, Any]=44_100 , lowerCamelCase_ :Optional[Any]=86 , lowerCamelCase_ :Dict=2_048 , lowerCamelCase_ :Union[str, Any]=0.0 , **lowerCamelCase_ :Tuple , ): """simple docstring""" super().__init__( feature_size=lowerCamelCase_ , sampling_rate=lowerCamelCase_ , padding_value=lowerCamelCase_ , **lowerCamelCase_ , ) lowerCamelCase__ : List[str] =spectrogram_length lowerCamelCase__ : Dict =num_channels lowerCamelCase__ : List[Any] =patch_size lowerCamelCase__ : Union[str, Any] =feature_size // self.patch_size[1] lowerCamelCase__ : int =n_fft lowerCamelCase__ : List[str] =sampling_rate // hop_length_to_sampling_rate lowerCamelCase__ : str =sampling_rate lowerCamelCase__ : int =padding_value lowerCamelCase__ : Dict =mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowerCamelCase_ , min_frequency=0.0 , max_frequency=2_20_50.0 , sampling_rate=lowerCamelCase_ , norm='slaney' , mel_scale='slaney' , ).T def UpperCAmelCase__ ( self :Dict , lowerCamelCase_ :np.array ): """simple docstring""" lowerCamelCase__ : List[Any] =spectrogram( lowerCamelCase_ , window_function(self.n_fft , 'hann' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='dB' , db_range=80.0 , ) lowerCamelCase__ : Any =log_spec[:, :-1] lowerCamelCase__ : Tuple =log_spec - 20.0 lowerCamelCase__ : List[str] =np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self :Optional[Any] , lowerCamelCase_ :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCamelCase_ :Optional[Union[str, TensorType]] = None , lowerCamelCase_ :Optional[bool] = True , lowerCamelCase_ :Optional[int] = None , lowerCamelCase_ :bool = False , lowerCamelCase_ :bool = False , **lowerCamelCase_ :Tuple , ): """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( 'This feature extractor is set to support sampling rate' f""" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled""" f""" with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) lowerCamelCase__ : Dict =isinstance(lowerCamelCase_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) lowerCamelCase__ : Union[str, Any] =is_batched_numpy or ( isinstance(lowerCamelCase_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCamelCase__ : Optional[Any] =[np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(lowerCamelCase_ , np.ndarray ): lowerCamelCase__ : Optional[Any] =np.asarray(lowerCamelCase_ , dtype=np.floataa ) elif isinstance(lowerCamelCase_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowerCamelCase__ : Union[str, Any] =raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowerCamelCase__ : List[str] =[np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis lowerCamelCase__ : Any =[ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , lowerCamelCase_ ): lowerCamelCase__ : Dict =[np.asarray(lowerCamelCase_ , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask lowerCamelCase__ : Optional[Any] =max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: lowerCamelCase__ : Any =[ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] lowerCamelCase__ : Union[str, Any] =np.array(lowerCamelCase_ ).astype(np.floataa ) # convert into correct format for padding lowerCamelCase__ : Tuple =max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch lowerCamelCase__ : str =np.ones([len(lowerCamelCase_ ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) lowerCamelCase__ : Dict =padded_audio_features * self.padding_value for i in range(len(lowerCamelCase_ ) ): lowerCamelCase__ : Union[str, Any] =audio_features[i] lowerCamelCase__ : Union[str, Any] =feature # return as BatchFeature if return_attention_mask: lowerCamelCase__ : int ={'audio_values': padded_audio_features, 'audio_mask': audio_mask} else: lowerCamelCase__ : Tuple ={'audio_values': padded_audio_features} lowerCamelCase__ : Union[str, Any] =BatchFeature(data=lowerCamelCase_ , tensor_type=lowerCamelCase_ ) return encoded_inputs
126
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : Any = logging.get_logger(__name__) __lowercase : str = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "sew-d" def __init__( self , __a=32 , __a=768 , __a=12 , __a=12 , __a=3072 , __a=2 , __a=512 , __a=256 , __a=True , __a=True , __a=("p2c", "c2p") , __a="layer_norm" , __a="gelu_python" , __a=0.1 , __a=0.1 , __a=0.1 , __a=0.0 , __a=0.1 , __a=0.02 , __a=1E-7 , __a=1E-5 , __a="group" , __a="gelu" , __a=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , __a=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , __a=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , __a=False , __a=128 , __a=16 , __a=True , __a=0.05 , __a=10 , __a=2 , __a=0.0 , __a=10 , __a=0 , __a="mean" , __a=False , __a=False , __a=256 , __a=0 , __a=1 , __a=2 , **__a , ): '''simple docstring''' super().__init__(**__a , pad_token_id=__a , bos_token_id=__a , eos_token_id=__a ) __a : Any = hidden_size __a : List[str] = feat_extract_norm __a : List[Any] = feat_extract_activation __a : Tuple = list(__a ) __a : Union[str, Any] = list(__a ) __a : List[Any] = list(__a ) __a : Dict = conv_bias __a : str = num_conv_pos_embeddings __a : Optional[Any] = num_conv_pos_embedding_groups __a : List[str] = len(self.conv_dim ) __a : str = num_hidden_layers __a : Any = intermediate_size __a : int = squeeze_factor __a : str = max_position_embeddings __a : int = position_buckets __a : Any = share_att_key __a : Dict = relative_attention __a : List[Any] = norm_rel_ebd __a : str = list(__a ) __a : Any = hidden_act __a : List[Any] = num_attention_heads __a : Dict = hidden_dropout __a : Optional[Any] = attention_dropout __a : List[str] = activation_dropout __a : Any = feat_proj_dropout __a : Dict = final_dropout __a : int = layer_norm_eps __a : Optional[Any] = feature_layer_norm_eps __a : Optional[int] = initializer_range __a : Optional[Any] = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f"""but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a : List[Any] = apply_spec_augment __a : int = mask_time_prob __a : int = mask_time_length __a : str = mask_time_min_masks __a : List[str] = mask_feature_prob __a : Optional[int] = mask_feature_length __a : Optional[int] = mask_feature_min_masks # ctc loss __a : Optional[Any] = ctc_loss_reduction __a : int = ctc_zero_infinity # sequence classification __a : int = use_weighted_layer_sum __a : Any = classifier_proj_size @property def __UpperCAmelCase ( self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
294
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys __lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
1
"""simple docstring""" def __UpperCAmelCase ( ): __lowercase : int = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] __lowercase : List[str] = 6 __lowercase : Optional[Any] = 1 __lowercase : str = 19_01 __lowercase : Dict = 0 while year < 20_01: day += 7 if (year % 4 == 0 and year % 1_00 != 0) or (year % 4_00 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 __lowercase : Optional[Any] = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 __lowercase : Dict = day - 29 else: if day > days_per_month[month - 1]: month += 1 __lowercase : Any = day - days_per_month[month - 2] if month > 12: year += 1 __lowercase : List[Any] = 1 if year < 20_01 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
249
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class UpperCAmelCase_ ( unittest.TestCase ): def _lowerCamelCase ( self ) -> Union[str, Any]: __lowercase : Dict = tempfile.mkdtemp() __lowercase : Any = BlipImageProcessor() __lowercase : Optional[int] = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' ) __lowercase : str = BertTokenizerFast.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) __lowercase : str = InstructBlipProcessor(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) processor.save_pretrained(self.tmpdirname ) def _lowerCamelCase ( self , **UpperCamelCase_ ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase_ ).tokenizer def _lowerCamelCase ( self , **UpperCamelCase_ ) -> List[str]: return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase_ ).image_processor def _lowerCamelCase ( self , **UpperCamelCase_ ) -> List[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase_ ).qformer_tokenizer def _lowerCamelCase ( self ) -> Tuple: shutil.rmtree(self.tmpdirname ) def _lowerCamelCase ( self ) -> Any: __lowercase : Optional[int] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowercase : Any = [Image.fromarray(np.moveaxis(UpperCamelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowerCamelCase ( self ) -> str: __lowercase : Any = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) __lowercase : List[str] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowercase : Dict = self.get_image_processor(do_normalize=UpperCamelCase_ , padding_value=1.0 ) __lowercase : int = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=UpperCamelCase_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCamelCase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCamelCase_ ) self.assertIsInstance(processor.qformer_tokenizer , UpperCamelCase_ ) def _lowerCamelCase ( self ) -> Any: __lowercase : Any = self.get_image_processor() __lowercase : str = self.get_tokenizer() __lowercase : Any = self.get_qformer_tokenizer() __lowercase : List[str] = InstructBlipProcessor( tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ , qformer_tokenizer=UpperCamelCase_ ) __lowercase : int = self.prepare_image_inputs() __lowercase : Union[str, Any] = image_processor(UpperCamelCase_ , return_tensors='''np''' ) __lowercase : Tuple = processor(images=UpperCamelCase_ , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _lowerCamelCase ( self ) -> str: __lowercase : str = self.get_image_processor() __lowercase : Dict = self.get_tokenizer() __lowercase : Optional[Any] = self.get_qformer_tokenizer() __lowercase : List[str] = InstructBlipProcessor( tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ , qformer_tokenizer=UpperCamelCase_ ) __lowercase : Dict = '''lower newer''' __lowercase : int = processor(text=UpperCamelCase_ ) __lowercase : List[str] = tokenizer(UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ ) __lowercase : Union[str, Any] = qformer_tokenizer(UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['''qformer_''' + key] ) def _lowerCamelCase ( self ) -> List[str]: __lowercase : Union[str, Any] = self.get_image_processor() __lowercase : Union[str, Any] = self.get_tokenizer() __lowercase : Optional[int] = self.get_qformer_tokenizer() __lowercase : List[str] = InstructBlipProcessor( tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ , qformer_tokenizer=UpperCamelCase_ ) __lowercase : Optional[int] = '''lower newer''' __lowercase : Any = self.prepare_image_inputs() __lowercase : List[Any] = processor(text=UpperCamelCase_ , images=UpperCamelCase_ ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , ) # test if it raises when no input is passed with pytest.raises(UpperCamelCase_ ): processor() def _lowerCamelCase ( self ) -> Dict: __lowercase : Any = self.get_image_processor() __lowercase : List[str] = self.get_tokenizer() __lowercase : Any = self.get_qformer_tokenizer() __lowercase : Tuple = InstructBlipProcessor( tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ , qformer_tokenizer=UpperCamelCase_ ) __lowercase : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowercase : List[str] = processor.batch_decode(UpperCamelCase_ ) __lowercase : Union[str, Any] = tokenizer.batch_decode(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) def _lowerCamelCase ( self ) -> List[str]: __lowercase : List[str] = self.get_image_processor() __lowercase : List[str] = self.get_tokenizer() __lowercase : List[Any] = self.get_qformer_tokenizer() __lowercase : Optional[Any] = InstructBlipProcessor( tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ , qformer_tokenizer=UpperCamelCase_ ) __lowercase : Any = '''lower newer''' __lowercase : Union[str, Any] = self.prepare_image_inputs() __lowercase : Union[str, Any] = processor(text=UpperCamelCase_ , images=UpperCamelCase_ ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , )
249
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _a : Optional[int] = logging.get_logger(__name__) class __A ( __lowercase ): _UpperCamelCase : Union[str, Any] = ["pixel_values"] def __init__( self , a__ = True , a__ = None , a__ = PIL.Image.BICUBIC , a__ = True , a__ = None , a__ = 1 / 255 , a__ = True , a__ = True , a__ = None , a__ = None , **a__ , ): super().__init__(**_a ) _lowerCAmelCase : Dict = size if size is not None else {'''height''': 256, '''width''': 256} _lowerCAmelCase : int = get_size_dict(_a ) _lowerCAmelCase : Tuple = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} _lowerCAmelCase : Dict = get_size_dict(_a , param_name="""crop_size""" ) _lowerCAmelCase : Union[str, Any] = do_resize _lowerCAmelCase : Any = size _lowerCAmelCase : List[Any] = resample _lowerCAmelCase : List[Any] = do_center_crop _lowerCAmelCase : Union[str, Any] = crop_size _lowerCAmelCase : str = do_rescale _lowerCAmelCase : Union[str, Any] = rescale_factor _lowerCAmelCase : int = do_normalize _lowerCAmelCase : List[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowerCAmelCase : Optional[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self , a__ , a__ , a__ = PIL.Image.BICUBIC , a__ = None , **a__ , ): _lowerCAmelCase : List[Any] = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}" ) return resize( _a , size=(size["""height"""], size["""width"""]) , resample=_a , data_format=_a , **_a ) def __A ( self , a__ , a__ , a__ = None , **a__ , ): _lowerCAmelCase : Union[str, Any] = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}" ) return 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__ = ChannelDimension.FIRST , **a__ , ): _lowerCAmelCase : int = do_resize if do_resize is not None else self.do_resize _lowerCAmelCase : int = resample if resample is not None else self.resample _lowerCAmelCase : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop _lowerCAmelCase : Any = do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase : List[Any] = do_normalize if do_normalize is not None else self.do_normalize _lowerCAmelCase : Optional[int] = image_mean if image_mean is not None else self.image_mean _lowerCAmelCase : Tuple = image_std if image_std is not None else self.image_std _lowerCAmelCase : Any = size if size is not None else self.size _lowerCAmelCase : str = get_size_dict(_a ) _lowerCAmelCase : List[Any] = crop_size if crop_size is not None else self.crop_size _lowerCAmelCase : int = get_size_dict(_a , param_name="""crop_size""" ) _lowerCAmelCase : Union[str, Any] = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. _lowerCAmelCase : Dict = [to_numpy_array(_a ) for image in images] if do_resize: _lowerCAmelCase : Optional[int] = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_center_crop: _lowerCAmelCase : Optional[Any] = [self.center_crop(image=_a , size=_a ) for image in images] if do_rescale: _lowerCAmelCase : Optional[Any] = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: _lowerCAmelCase : Dict = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] _lowerCAmelCase : Tuple = [to_channel_dimension_format(_a , _a ) for image in images] _lowerCAmelCase : Dict = {'''pixel_values''': images} return BatchFeature(data=_a , tensor_type=_a )
365
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _a : List[Any] = logging.get_logger(__name__) class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = "maskformer-swin" _UpperCamelCase : Union[str, Any] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=None , a__=None , **a__ , ): super().__init__(**a__ ) _lowerCAmelCase : Dict = image_size _lowerCAmelCase : List[str] = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : int = embed_dim _lowerCAmelCase : Optional[Any] = depths _lowerCAmelCase : List[str] = len(a__ ) _lowerCAmelCase : List[Any] = num_heads _lowerCAmelCase : Tuple = window_size _lowerCAmelCase : List[Any] = mlp_ratio _lowerCAmelCase : Optional[Any] = qkv_bias _lowerCAmelCase : int = hidden_dropout_prob _lowerCAmelCase : Union[str, Any] = attention_probs_dropout_prob _lowerCAmelCase : Any = drop_path_rate _lowerCAmelCase : Optional[Any] = hidden_act _lowerCAmelCase : Tuple = use_absolute_embeddings _lowerCAmelCase : str = layer_norm_eps _lowerCAmelCase : Any = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase : Union[str, Any] = int(embed_dim * 2 ** (len(a__ ) - 1) ) _lowerCAmelCase : int = ["""stem"""] + [F"stage{idx}" for idx in range(1 , len(a__ ) + 1 )] _lowerCAmelCase , _lowerCAmelCase : int = get_aligned_output_features_output_indices( out_features=a__ , out_indices=a__ , stage_names=self.stage_names )
126
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _lowercase ( unittest.TestCase ): '''simple docstring''' def __magic_name__( self :int ) -> Any: __SCREAMING_SNAKE_CASE : Optional[int] = inspect.getfile(accelerate.test_utils ) __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __SCREAMING_SNAKE_CASE : int = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __magic_name__( self :Optional[int] ) -> Any: print(f'''Found {torch.cuda.device_count()} devices.''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() ) @require_multi_gpu def __magic_name__( self :Optional[int] ) -> Tuple: print(f'''Found {torch.cuda.device_count()} devices.''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() ) @require_multi_gpu def __magic_name__( self :Tuple ) -> Dict: __SCREAMING_SNAKE_CASE : Optional[Any] = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() ) @require_multi_gpu def __magic_name__( self :str ) -> int: print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __SCREAMING_SNAKE_CASE : Dict = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() ) if __name__ == "__main__": __lowerCAmelCase : Dict =Accelerator() __lowerCAmelCase : Any =(accelerator.state.process_index + 2, 1_0) __lowerCAmelCase : List[Any] =torch.randint(0, 1_0, shape).to(accelerator.device) __lowerCAmelCase : Tuple ='' __lowerCAmelCase : Union[str, Any] =accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __lowerCAmelCase : Union[str, Any] =accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __lowerCAmelCase : Optional[int] =accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
9
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract __lowerCAmelCase : List[str] = logging.get_logger(__name__) def __magic_name__ ( A : Dict, A : int, A : Optional[int] ): '''simple docstring''' return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def __magic_name__ ( A : np.ndarray, A : Optional[str], A : Optional[str] = None ): '''simple docstring''' a = tesseract_config if tesseract_config is not None else "" # apply OCR a = to_pil_image(A ) a , a = pil_image.size a = pytesseract.image_to_data(A, lang=A, output_type="dict", config=A ) a , a , a , a , a = data["text"], data["left"], data["top"], data["width"], data["height"] # filter empty words and corresponding coordinates a = [idx for idx, word in enumerate(A ) if not word.strip()] a = [word for idx, word in enumerate(A ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(A ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(A ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(A ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(A ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format a = [] for x, y, w, h in zip(A, A, A, A ): a = [x, y, x + w, y + h] actual_boxes.append(A ) # finally, normalize the bounding boxes a = [] for box in actual_boxes: normalized_boxes.append(normalize_box(A, A, A ) ) assert len(A ) == len(A ), "Not as many words as there are bounding boxes" return words, normalized_boxes class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = ["""pixel_values"""] def __init__( self : int , __lowerCamelCase : bool = True , __lowerCamelCase : Dict[str, int] = None , __lowerCamelCase : PILImageResampling = PILImageResampling.BILINEAR , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[str] = None , __lowerCamelCase : Optional[str] = "" , **__lowerCamelCase : Tuple , ) -> None: super().__init__(**__lowerCamelCase ) a = size if size is not None else {"height": 2_24, "width": 2_24} a = get_size_dict(__lowerCamelCase ) a = do_resize a = size a = resample a = apply_ocr a = ocr_lang a = tesseract_config def __UpperCAmelCase ( self : Dict , __lowerCamelCase : np.ndarray , __lowerCamelCase : Dict[str, int] , __lowerCamelCase : PILImageResampling = PILImageResampling.BILINEAR , __lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCamelCase : Optional[int] , ) -> np.ndarray: a = get_size_dict(__lowerCamelCase ) 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()}""" ) a = (size["height"], size["width"]) return resize(__lowerCamelCase , size=__lowerCamelCase , resample=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : ImageInput , __lowerCamelCase : bool = None , __lowerCamelCase : Dict[str, int] = None , __lowerCamelCase : PILImageResampling = None , __lowerCamelCase : bool = None , __lowerCamelCase : Optional[str] = None , __lowerCamelCase : Optional[str] = None , __lowerCamelCase : Optional[Union[str, TensorType]] = None , __lowerCamelCase : ChannelDimension = ChannelDimension.FIRST , **__lowerCamelCase : Optional[Any] , ) -> PIL.Image.Image: a = do_resize if do_resize is not None else self.do_resize a = size if size is not None else self.size a = get_size_dict(__lowerCamelCase ) a = resample if resample is not None else self.resample a = apply_ocr if apply_ocr is not None else self.apply_ocr a = ocr_lang if ocr_lang is not None else self.ocr_lang a = tesseract_config if tesseract_config is not None else self.tesseract_config a = 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: raise ValueError("Size must be specified if do_resize is True." ) # All transformations expect numpy arrays. a = [to_numpy_array(__lowerCamelCase ) for image in images] if apply_ocr: requires_backends(self , "pytesseract" ) a = [] a = [] for image in images: a , a = apply_tesseract(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) words_batch.append(__lowerCamelCase ) boxes_batch.append(__lowerCamelCase ) if do_resize: a = [self.resize(image=__lowerCamelCase , size=__lowerCamelCase , resample=__lowerCamelCase ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) a = [flip_channel_order(__lowerCamelCase ) for image in images] a = [to_channel_dimension_format(__lowerCamelCase , __lowerCamelCase ) for image in images] a = BatchFeature(data={"pixel_values": images} , tensor_type=__lowerCamelCase ) if apply_ocr: a = words_batch a = boxes_batch return data
107
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( lowerCAmelCase__ , unittest.TestCase ): __a = DiTPipeline __a = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS __a = PipelineTesterMixin.required_optional_params - { "latents", "num_images_per_prompt", "callback", "callback_steps", } __a = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS __a = False def lowercase ( self : int ): torch.manual_seed(0 ) _snake_case = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=a__ , activation_fn='''gelu-approximate''' , num_embeds_ada_norm=1000 , norm_type='''ada_norm_zero''' , norm_elementwise_affine=a__ , ) _snake_case = AutoencoderKL() _snake_case = DDIMScheduler() _snake_case = {'''transformer''': transformer.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler} return components def lowercase ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : List[Any]=0 ): if str(a__ ).startswith('''mps''' ): _snake_case = torch.manual_seed(a__ ) else: _snake_case = torch.Generator(device=a__ ).manual_seed(a__ ) _snake_case = { '''class_labels''': [1], '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def lowercase ( self : int ): _snake_case = '''cpu''' _snake_case = self.get_dummy_components() _snake_case = self.pipeline_class(**a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _snake_case = self.get_dummy_inputs(a__ ) _snake_case = pipe(**a__ ).images _snake_case = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) _snake_case = np.array([0.2_9_4_6, 0.6_6_0_1, 0.4_3_2_9, 0.3_2_9_6, 0.4_1_4_4, 0.5_3_1_9, 0.7_2_7_3, 0.5_0_1_3, 0.4_4_5_7] ) _snake_case = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a__ , 1e-3 ) def lowercase ( self : Any ): self._test_inference_batch_single_identical(relax_max_difference=a__ , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def lowercase ( self : List[Any] ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): def lowercase ( self : Dict ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : Optional[int] ): _snake_case = torch.manual_seed(0 ) _snake_case = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-256''' ) pipe.to('''cuda''' ) _snake_case = ['''vase''', '''umbrella''', '''white shark''', '''white wolf'''] _snake_case = pipe.get_label_ids(a__ ) _snake_case = pipe(a__ , generator=a__ , num_inference_steps=40 , output_type='''np''' ).images for word, image in zip(a__ , a__ ): _snake_case = load_numpy( f'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-2 def lowercase ( self : str ): _snake_case = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-512''' ) _snake_case = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('''cuda''' ) _snake_case = ['''vase''', '''umbrella'''] _snake_case = pipe.get_label_ids(a__ ) _snake_case = torch.manual_seed(0 ) _snake_case = pipe(a__ , generator=a__ , num_inference_steps=25 , output_type='''np''' ).images for word, image in zip(a__ , a__ ): _snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' f'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-1
363
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class lowerCAmelCase__ : def __init__( self : Any , _lowerCamelCase : Optional[Any] , ): _snake_case = parent _snake_case = 13 _snake_case = 7 _snake_case = 30 _snake_case = self.seq_length + self.mem_len _snake_case = 15 _snake_case = True _snake_case = True _snake_case = 99 _snake_case = [10, 50, 80] _snake_case = 32 _snake_case = 32 _snake_case = 4 _snake_case = 8 _snake_case = 128 _snake_case = 2 _snake_case = 2 _snake_case = None _snake_case = 1 _snake_case = 0 _snake_case = 3 _snake_case = self.vocab_size - 1 _snake_case = 0.0_1 def lowercase ( self : Optional[int] ): _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = None if self.use_labels: _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def lowercase ( self : Any ): random.seed(self.seed ) tf.random.set_seed(self.seed ) def lowercase ( self : Dict , _lowerCamelCase : int , _lowerCamelCase : List[Any] , _lowerCamelCase : Dict , _lowerCamelCase : List[str] ): _snake_case = TFTransfoXLModel(_lowerCamelCase ) _snake_case , _snake_case = model(_lowerCamelCase ).to_tuple() _snake_case = {'''input_ids''': input_ids_a, '''mems''': mems_a} _snake_case , _snake_case = model(_lowerCamelCase ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def lowercase ( self : List[Any] , _lowerCamelCase : Dict , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Tuple ): _snake_case = TFTransfoXLLMHeadModel(_lowerCamelCase ) _snake_case , _snake_case = model(_lowerCamelCase ).to_tuple() _snake_case = {'''input_ids''': input_ids_a, '''labels''': lm_labels} _snake_case , _snake_case = model(_lowerCamelCase ).to_tuple() _snake_case , _snake_case = model([input_ids_a, mems_a] ).to_tuple() _snake_case = {'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels} _snake_case , _snake_case = model(_lowerCamelCase ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def lowercase ( self : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : List[str] ): _snake_case = TFTransfoXLForSequenceClassification(_lowerCamelCase ) _snake_case = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase ( self : str ): _snake_case = self.prepare_config_and_inputs() ((_snake_case) , (_snake_case) , (_snake_case) , (_snake_case)) = config_and_inputs _snake_case = {'''input_ids''': input_ids_a} return config, inputs_dict @require_tf class lowerCAmelCase__ ( A_ , A_ , unittest.TestCase ): __a = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) __a = () if is_tf_available() else () __a = ( { """feature-extraction""": TFTransfoXLModel, """text-classification""": TFTransfoXLForSequenceClassification, """text-generation""": TFTransfoXLLMHeadModel, """zero-shot""": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented __a = False __a = False __a = False __a = False def lowercase ( self : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : List[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Union[str, Any] ): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def lowercase ( self : List[Any] ): _snake_case = TFTransfoXLModelTester(self ) _snake_case = ConfigTester(self , config_class=_lowerCamelCase , d_embed=37 ) def lowercase ( self : List[str] ): self.config_tester.run_common_tests() def lowercase ( self : Union[str, Any] ): self.model_tester.set_seed() _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*_lowerCamelCase ) def lowercase ( self : str ): self.model_tester.set_seed() _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*_lowerCamelCase ) def lowercase ( self : str ): _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*_lowerCamelCase ) def lowercase ( self : str ): _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common() _snake_case = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: _snake_case = model_class(_lowerCamelCase ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: _snake_case = model.get_output_embeddings() assert isinstance(_lowerCamelCase , tf.keras.layers.Layer ) _snake_case = model.get_bias() assert name is None else: _snake_case = model.get_output_embeddings() assert x is None _snake_case = model.get_bias() assert name is None def lowercase ( self : Optional[Any] ): # TODO JP: Make TransfoXL XLA compliant pass @slow def lowercase ( self : int ): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = TFTransfoXLModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @unittest.skip(reason='''This model doesn\'t play well with fit() due to not returning a single loss.''' ) def lowercase ( self : int ): pass @require_tf class lowerCAmelCase__ ( unittest.TestCase ): @unittest.skip('''Skip test until #12651 is resolved.''' ) @slow def lowercase ( self : List[Any] ): _snake_case = TFTransfoXLLMHeadModel.from_pretrained('''transfo-xl-wt103''' ) # fmt: off _snake_case = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,11739,4762,358,5,25,245,22,1706,17,20098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,6224,831,16002,2,8,603,78967,29546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,29546,54,8,3609,5,57211,49,4,1,277,18,8,1755,15691,3,341,25,416,693,42573,71,17,401,94,31,17919,2,29546,7873,18,1,435,23,11011,755,5,5167,3,7983,98,84,2,29546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,29546,824,1400,1868,2,19,160,2,311,8,5496,2,20920,17,25,15097,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off _snake_case = [33,1297,2,1,1009,4,1109,11739,4762,358,5,25,245,22,1706,17,20098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,6224,831,16002,2,8,603,78967,29546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,29546,54,8,3609,5,57211,49,4,1,277,18,8,1755,15691,3,341,25,416,693,42573,71,17,401,94,31,17919,2,29546,7873,18,1,435,23,11011,755,5,5167,3,7983,98,84,2,29546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,29546,824,1400,1868,2,19,160,2,311,8,5496,2,20920,17,25,15097,3,24,24,0,33,1,1857,2,1,1009,4,1109,11739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> _snake_case = model.generate(_lowerCamelCase , max_length=200 , do_sample=_lowerCamelCase ) self.assertListEqual(output_ids[0].numpy().tolist() , _lowerCamelCase )
40
0
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a : Dict = logging.get_logger(__name__) class _a ( _lowerCAmelCase ): def __init__(self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCAmelCase_: Tuple = feature_size UpperCAmelCase_: List[str] = sampling_rate UpperCAmelCase_: str = padding_value UpperCAmelCase_: List[Any] = kwargs.pop("""padding_side""", """right""" ) UpperCAmelCase_: Optional[int] = kwargs.pop("""return_attention_mask""", SCREAMING_SNAKE_CASE_ ) super().__init__(**SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = False, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE_, (list, tuple) ) and isinstance(processed_features[0], (dict, BatchFeature) ): UpperCAmelCase_: Union[str, Any] = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( """You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`""" f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) UpperCAmelCase_: Dict = processed_features[self.model_input_names[0]] UpperCAmelCase_: str = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE_ ) == 0: if return_attention_mask: UpperCAmelCase_: Optional[Any] = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch UpperCAmelCase_: int = required_input[0] if isinstance(SCREAMING_SNAKE_CASE_, (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. UpperCAmelCase_: int = 0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE_ ): UpperCAmelCase_: Any = required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE_ ): UpperCAmelCase_: int = """tf""" elif is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCAmelCase_: str = """pt""" elif isinstance(SCREAMING_SNAKE_CASE_, (int, float, list, tuple, np.ndarray) ): UpperCAmelCase_: Dict = """np""" else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE_ )}. ' """Should be one of a python, numpy, pytorch or tensorflow object.""" ) for key, value in processed_features.items(): if isinstance(value[0], (int, float) ): UpperCAmelCase_: Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) else: UpperCAmelCase_: List[Any] = [to_numpy(SCREAMING_SNAKE_CASE_ ) for v in value] # Convert padding_strategy in PaddingStrategy UpperCAmelCase_: List[Any] = self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Any = processed_features[self.model_input_names[0]] UpperCAmelCase_: str = len(SCREAMING_SNAKE_CASE_ ) if not all(len(SCREAMING_SNAKE_CASE_ ) == batch_size for v in processed_features.values() ): raise ValueError("""Some items in the output dictionary have a different batch size than others.""" ) UpperCAmelCase_: List[str] = [] for i in range(SCREAMING_SNAKE_CASE_ ): UpperCAmelCase_: Union[str, Any] = {k: v[i] for k, v in processed_features.items()} # truncation UpperCAmelCase_: Dict = self._truncate( SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_, pad_to_multiple_of=SCREAMING_SNAKE_CASE_, truncation=SCREAMING_SNAKE_CASE_, ) truncated_inputs.append(SCREAMING_SNAKE_CASE_ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length UpperCAmelCase_: List[Any] = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) UpperCAmelCase_: Tuple = PaddingStrategy.MAX_LENGTH UpperCAmelCase_: List[str] = {} for i in range(SCREAMING_SNAKE_CASE_ ): # padding UpperCAmelCase_: List[Any] = self._pad( truncated_inputs[i], max_length=SCREAMING_SNAKE_CASE_, padding_strategy=SCREAMING_SNAKE_CASE_, pad_to_multiple_of=SCREAMING_SNAKE_CASE_, return_attention_mask=SCREAMING_SNAKE_CASE_, ) for key, value in outputs.items(): if key not in batch_outputs: UpperCAmelCase_: List[str] = [] if value.dtype is np.dtype(np.floataa ): UpperCAmelCase_: int = value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE_ ) return BatchFeature(SCREAMING_SNAKE_CASE_, tensor_type=SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = PaddingStrategy.DO_NOT_PAD, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, ) -> dict: UpperCAmelCase_: int = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: UpperCAmelCase_: int = len(SCREAMING_SNAKE_CASE_ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): UpperCAmelCase_: Dict = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of UpperCAmelCase_: Union[str, Any] = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE_ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: UpperCAmelCase_: Dict = np.ones(len(SCREAMING_SNAKE_CASE_ ), dtype=np.intaa ) if needs_to_be_padded: UpperCAmelCase_: List[Any] = max_length - len(SCREAMING_SNAKE_CASE_ ) if self.padding_side == "right": if return_attention_mask: UpperCAmelCase_: Tuple = np.pad( processed_features["""attention_mask"""], (0, difference) ) UpperCAmelCase_: Optional[int] = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) UpperCAmelCase_: List[Any] = np.pad( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, """constant""", constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: UpperCAmelCase_: Optional[int] = np.pad( processed_features["""attention_mask"""], (difference, 0) ) UpperCAmelCase_: str = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) UpperCAmelCase_: Optional[int] = np.pad( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, """constant""", constant_values=self.padding_value ) else: raise ValueError("""Invalid padding strategy:""" + str(self.padding_side ) ) return processed_features def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, ) -> Union[str, Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("""When setting ``truncation=True``, make sure that ``max_length`` is defined.""" ) UpperCAmelCase_: List[Any] = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): UpperCAmelCase_: Dict = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of UpperCAmelCase_: List[str] = len(SCREAMING_SNAKE_CASE_ ) > max_length if needs_to_be_truncated: UpperCAmelCase_: List[str] = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: UpperCAmelCase_: Optional[Any] = processed_features["""attention_mask"""][:max_length] return processed_features def __snake_case (self, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=None ) -> Optional[int]: # Get padding strategy if padding is not False: if padding is True: UpperCAmelCase_: Optional[int] = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): UpperCAmelCase_: List[Any] = PaddingStrategy(SCREAMING_SNAKE_CASE_ ) elif isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): UpperCAmelCase_: Optional[int] = padding else: UpperCAmelCase_: Optional[Any] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( """Asking to pad but the feature_extractor does not have a padding value. Please select a value to use""" """ as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.""" ) return padding_strategy
147
from torch import nn def lowerCAmelCase_ (lowerCAmelCase__: Optional[int] ): """simple docstring""" if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'Unsupported activation function: {act_fn}' )
147
1
'''simple docstring''' import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCamelCase__( lowerCAmelCase ): __magic_name__ : Optional[int] = (DDIMParallelScheduler,) __magic_name__ : Any = (("eta", 0.0), ("num_inference_steps", 50)) def a__( self : List[Any] , **lowerCAmelCase : Optional[int] )-> Dict: """simple docstring""" UpperCAmelCase = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**lowerCAmelCase ) return config def a__( self : Union[str, Any] , **lowerCAmelCase : Optional[Any] )-> Tuple: """simple docstring""" UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(**lowerCAmelCase ) UpperCAmelCase = scheduler_class(**lowerCAmelCase ) UpperCAmelCase , UpperCAmelCase = 10, 0.0 UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter scheduler.set_timesteps(lowerCAmelCase ) for t in scheduler.timesteps: UpperCAmelCase = model(lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase = scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).prev_sample return sample def a__( self : str )-> str: """simple docstring""" for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=lowerCAmelCase ) def a__( self : Optional[int] )-> List[Any]: """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowerCAmelCase ) UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(steps_offset=1 ) UpperCAmelCase = scheduler_class(**lowerCAmelCase ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def a__( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowerCAmelCase , beta_end=lowerCAmelCase ) def a__( self : str )-> List[Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCAmelCase ) def a__( self : int )-> str: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase ) def a__( self : List[Any] )-> Any: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCAmelCase ) def a__( self : Union[str, Any] )-> List[str]: """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=lowerCAmelCase ) def a__( self : int )-> Tuple: """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=lowerCAmelCase ) def a__( self : int )-> Tuple: """simple docstring""" self.check_over_configs(thresholding=lowerCAmelCase ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=lowerCAmelCase , prediction_type=lowerCAmelCase , sample_max_value=lowerCAmelCase , ) def a__( self : Union[str, Any] )-> Tuple: """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=lowerCAmelCase ) def a__( self : Tuple )-> Dict: """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=lowerCAmelCase , num_inference_steps=lowerCAmelCase ) def a__( self : Dict )-> Tuple: """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=lowerCAmelCase , eta=lowerCAmelCase ) def a__( self : Optional[int] )-> Optional[int]: """simple docstring""" UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowerCAmelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14771 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32460 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1E-5 def a__( self : str )-> List[str]: """simple docstring""" UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowerCAmelCase ) UpperCAmelCase , UpperCAmelCase = 10, 0.0 scheduler.set_timesteps(lowerCAmelCase ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter UpperCAmelCase = self.dummy_sample_deter + 0.1 UpperCAmelCase = self.dummy_sample_deter - 0.1 UpperCAmelCase = samplea.shape[0] UpperCAmelCase = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCAmelCase = torch.arange(lowerCAmelCase )[0:3, None].repeat(1 , lowerCAmelCase ) UpperCAmelCase = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCAmelCase = scheduler.batch_step_no_noise(lowerCAmelCase , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , lowerCAmelCase ) UpperCAmelCase = torch.sum(torch.abs(lowerCAmelCase ) ) UpperCAmelCase = torch.mean(torch.abs(lowerCAmelCase ) ) assert abs(result_sum.item() - 1147.7904 ) < 1E-2 assert abs(result_mean.item() - 0.4982 ) < 1E-3 def a__( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" UpperCAmelCase = self.full_loop() UpperCAmelCase = torch.sum(torch.abs(lowerCAmelCase ) ) UpperCAmelCase = torch.mean(torch.abs(lowerCAmelCase ) ) assert abs(result_sum.item() - 172.0067 ) < 1E-2 assert abs(result_mean.item() - 0.223967 ) < 1E-3 def a__( self : Optional[Any] )-> Dict: """simple docstring""" UpperCAmelCase = self.full_loop(prediction_type='''v_prediction''' ) UpperCAmelCase = torch.sum(torch.abs(lowerCAmelCase ) ) UpperCAmelCase = torch.mean(torch.abs(lowerCAmelCase ) ) assert abs(result_sum.item() - 52.5302 ) < 1E-2 assert abs(result_mean.item() - 0.0684 ) < 1E-3 def a__( self : Dict )-> Any: """simple docstring""" UpperCAmelCase = self.full_loop(set_alpha_to_one=lowerCAmelCase , beta_start=0.01 ) UpperCAmelCase = torch.sum(torch.abs(lowerCAmelCase ) ) UpperCAmelCase = torch.mean(torch.abs(lowerCAmelCase ) ) assert abs(result_sum.item() - 149.8295 ) < 1E-2 assert abs(result_mean.item() - 0.1951 ) < 1E-3 def a__( self : Optional[int] )-> int: """simple docstring""" UpperCAmelCase = self.full_loop(set_alpha_to_one=lowerCAmelCase , beta_start=0.01 ) UpperCAmelCase = torch.sum(torch.abs(lowerCAmelCase ) ) UpperCAmelCase = torch.mean(torch.abs(lowerCAmelCase ) ) assert abs(result_sum.item() - 149.0784 ) < 1E-2 assert abs(result_mean.item() - 0.1941 ) < 1E-3
357
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int = logging.get_logger(__name__) _lowercase : Optional[Any] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class UpperCamelCase__( lowerCAmelCase ): __magic_name__ : Union[str, Any] = "openai-gpt" __magic_name__ : Optional[int] = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Optional[int] , lowerCAmelCase : Optional[Any]=40478 , lowerCAmelCase : str=512 , lowerCAmelCase : List[Any]=768 , lowerCAmelCase : Tuple=12 , lowerCAmelCase : int=12 , lowerCAmelCase : List[str]="gelu" , lowerCAmelCase : List[str]=0.1 , lowerCAmelCase : List[Any]=0.1 , lowerCAmelCase : Dict=0.1 , lowerCAmelCase : Tuple=1E-5 , lowerCAmelCase : Tuple=0.02 , lowerCAmelCase : Optional[int]="cls_index" , lowerCAmelCase : Dict=True , lowerCAmelCase : Optional[int]=None , lowerCAmelCase : Dict=True , lowerCAmelCase : int=0.1 , **lowerCAmelCase : Optional[int] , )-> str: """simple docstring""" UpperCAmelCase = vocab_size UpperCAmelCase = n_positions UpperCAmelCase = n_embd UpperCAmelCase = n_layer UpperCAmelCase = n_head UpperCAmelCase = afn UpperCAmelCase = resid_pdrop UpperCAmelCase = embd_pdrop UpperCAmelCase = attn_pdrop UpperCAmelCase = layer_norm_epsilon UpperCAmelCase = initializer_range UpperCAmelCase = summary_type UpperCAmelCase = summary_use_proj UpperCAmelCase = summary_activation UpperCAmelCase = summary_first_dropout UpperCAmelCase = summary_proj_to_labels super().__init__(**lowerCAmelCase )
91
0
import numpy as np import qiskit def SCREAMING_SNAKE_CASE__ ( __a = 8 , __a = None ): snake_case_ : str = np.random.default_rng(seed=__a ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. snake_case_ : Tuple = 6 * key_len # Measurement basis for Alice's qubits. snake_case_ : Optional[Any] = rng.integers(2 , size=__a ) # The set of states Alice will prepare. snake_case_ : str = rng.integers(2 , size=__a ) # Measurement basis for Bob's qubits. snake_case_ : str = rng.integers(2 , size=__a ) # Quantum Circuit to simulate BB84 snake_case_ : str = qiskit.QuantumCircuit(__a , name='BB84' ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__a ): if alice_state[index] == 1: bbaa_circ.x(__a ) if alice_basis[index] == 1: bbaa_circ.h(__a ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__a ): if bob_basis[index] == 1: bbaa_circ.h(__a ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. snake_case_ : Optional[Any] = qiskit.Aer.get_backend('aer_simulator' ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. snake_case_ : List[str] = qiskit.execute(__a , __a , shots=1 , seed_simulator=__a ) # Returns the result of measurement. snake_case_ : Union[str, Any] = job.result().get_counts(__a ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. snake_case_ : int = ''.join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __a , __a , __a ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. snake_case_ : Dict = gen_key[:key_len] if len(__a ) >= key_len else gen_key.ljust(__a , '0' ) return key if __name__ == "__main__": print(F'''The generated key is : {bbaa(8, seed=0)}''') from doctest import testmod testmod()
327
def SCREAMING_SNAKE_CASE__ ( __a , __a ): while b: snake_case_ ,snake_case_ : Any = b, a % b return a def SCREAMING_SNAKE_CASE__ ( __a , __a ): return a if b == 0 else euclidean_gcd_recursive(__a , a % b ) def SCREAMING_SNAKE_CASE__ ( ): print(f"""euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}""" ) print(f"""euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}""" ) print(f"""euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}""" ) print(f"""euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}""" ) print(f"""euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}""" ) print(f"""euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}""" ) print(f"""euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}""" ) print(f"""euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}""" ) print(f"""euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}""" ) print(f"""euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}""" ) if __name__ == "__main__": main()
327
1
'''simple docstring''' def a_ ( _UpperCAmelCase : list ,_UpperCAmelCase : int ,_UpperCAmelCase : int = 0 ,_UpperCAmelCase : int = 0 ) -> int: __snake_case : List[str] = right or len(lowercase__ ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(lowercase__ ,lowercase__ ,left + 1 ,right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
350
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class _A ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : str=7 , __UpperCAmelCase : str=3 , __UpperCAmelCase : Tuple=18 , __UpperCAmelCase : Dict=30 , __UpperCAmelCase : Any=400 , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : Tuple=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __UpperCAmelCase : Optional[Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __UpperCAmelCase : Union[str, Any]=True , ): a : int = size if size is not None else {"height": 224, "width": 224} a : List[str] = crop_size if crop_size is not None else {"height": 18, "width": 18} a : List[Any] = parent a : Any = batch_size a : str = num_channels a : Optional[int] = image_size a : Tuple = min_resolution a : str = max_resolution a : Dict = do_resize a : Any = size a : Dict = do_center_crop a : List[str] = crop_size a : str = do_normalize a : Optional[int] = image_mean a : Tuple = image_std a : Any = do_convert_rgb def __snake_case ( self : Union[str, Any]): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __snake_case ( self : Dict , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : List[Any]=False , __UpperCAmelCase : Any=False): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: a : str = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: a : Tuple = [] for i in range(self.batch_size): a , a : List[str] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension a : List[Any] = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1)) for x in image_inputs] if torchify: a : Optional[Any] = [torch.from_numpy(__UpperCAmelCase) for x in image_inputs] return image_inputs @require_torch @require_vision class _A ( _a ,unittest.TestCase ): """simple docstring""" UpperCAmelCase : Union[str, Any] = ChineseCLIPImageProcessor if is_vision_available() else None def __snake_case ( self : List[str]): a : Dict = ChineseCLIPImageProcessingTester(self , do_center_crop=__UpperCAmelCase) @property def __snake_case ( self : Union[str, Any]): return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : str): a : Optional[int] = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__UpperCAmelCase , "do_resize")) self.assertTrue(hasattr(__UpperCAmelCase , "size")) self.assertTrue(hasattr(__UpperCAmelCase , "do_center_crop")) self.assertTrue(hasattr(__UpperCAmelCase , "center_crop")) self.assertTrue(hasattr(__UpperCAmelCase , "do_normalize")) self.assertTrue(hasattr(__UpperCAmelCase , "image_mean")) self.assertTrue(hasattr(__UpperCAmelCase , "image_std")) self.assertTrue(hasattr(__UpperCAmelCase , "do_convert_rgb")) def __snake_case ( self : Any): a : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {"height": 224, "width": 224}) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18}) a : int = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84) self.assertEqual(image_processor.size , {"shortest_edge": 42}) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84}) def __snake_case ( self : str): pass def __snake_case ( self : Tuple): # Initialize image_processing a : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images a : Any = self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCAmelCase) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image) # Test not batched input a : str = image_processing(image_inputs[0] , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a : Dict = image_processing(__UpperCAmelCase , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __snake_case ( self : List[Any]): # Initialize image_processing a : str = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors a : Any = self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray) # Test not batched input a : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a : Union[str, Any] = image_processing(__UpperCAmelCase , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __snake_case ( self : List[str]): # Initialize image_processing a : str = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors a : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor) # Test not batched input a : List[str] = image_processing(image_inputs[0] , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a : str = image_processing(__UpperCAmelCase , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class _A ( _a ,unittest.TestCase ): """simple docstring""" UpperCAmelCase : Optional[int] = ChineseCLIPImageProcessor if is_vision_available() else None def __snake_case ( self : Union[str, Any]): a : str = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__UpperCAmelCase) a : Dict = 3 @property def __snake_case ( self : Optional[Any]): return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Optional[int]): a : Tuple = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__UpperCAmelCase , "do_resize")) self.assertTrue(hasattr(__UpperCAmelCase , "size")) self.assertTrue(hasattr(__UpperCAmelCase , "do_center_crop")) self.assertTrue(hasattr(__UpperCAmelCase , "center_crop")) self.assertTrue(hasattr(__UpperCAmelCase , "do_normalize")) self.assertTrue(hasattr(__UpperCAmelCase , "image_mean")) self.assertTrue(hasattr(__UpperCAmelCase , "image_std")) self.assertTrue(hasattr(__UpperCAmelCase , "do_convert_rgb")) def __snake_case ( self : Any): pass def __snake_case ( self : Union[str, Any]): # Initialize image_processing a : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images a : str = self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCAmelCase) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image) # Test not batched input a : Tuple = image_processing(image_inputs[0] , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a : Optional[Any] = image_processing(__UpperCAmelCase , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
40
"""simple docstring""" from __future__ import annotations class _A : """simple docstring""" def __init__( self : List[str] , __UpperCAmelCase : int = 0): a : Tuple = key def __snake_case ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : int): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(__UpperCAmelCase) ^ key) for ch in content] def __snake_case ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : int): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : Optional[Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(__UpperCAmelCase) ^ key) for ch in content] def __snake_case ( self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : int = 0): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : List[Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned a : Any = "" for ch in content: ans += chr(ord(__UpperCAmelCase) ^ key) return ans def __snake_case ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : int = 0): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : Dict = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned a : str = "" for ch in content: ans += chr(ord(__UpperCAmelCase) ^ key) return ans def __snake_case ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : int = 0): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) try: with open(__UpperCAmelCase) as fin, open("encrypt.out" , "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(__UpperCAmelCase , __UpperCAmelCase)) except OSError: return False return True def __snake_case ( self : Any , __UpperCAmelCase : str , __UpperCAmelCase : int): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) try: with open(__UpperCAmelCase) as fin, open("decrypt.out" , "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(__UpperCAmelCase , __UpperCAmelCase)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
40
1
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any ) -> Optional[int]: """simple docstring""" UpperCamelCase :int = filter(lambda __magic_name__ : p.requires_grad , model.parameters() ) UpperCamelCase :List[str] = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCAmelCase_ : List[Any] = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : Dict ) -> Union[str, Any]: """simple docstring""" if metric == "rouge2": UpperCamelCase :str = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": UpperCamelCase :Dict = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": UpperCamelCase :List[Any] = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( f"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this""" """ function.""" ) UpperCamelCase :Any = ModelCheckpoint( dirpath=__magic_name__ , filename=__magic_name__ , monitor=f"""val_{metric}""" , mode="""max""" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] ) -> Dict: """simple docstring""" return EarlyStopping( monitor=f"""val_{metric}""" , mode="""min""" if """loss""" in metric else """max""" , patience=__magic_name__ , verbose=__magic_name__ , ) class _SCREAMING_SNAKE_CASE ( pl.Callback ): def _A ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] ): UpperCamelCase :List[Any] = {F"""lr_group_{i}""": param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__lowerCamelCase ) @rank_zero_only def _A ( self : int , __lowerCamelCase : pl.Trainer , __lowerCamelCase : pl.LightningModule , __lowerCamelCase : str , __lowerCamelCase : List[str]=True ): logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) UpperCamelCase :Optional[Any] = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results UpperCamelCase :int = Path(pl_module.hparams.output_dir ) if type_path == "test": UpperCamelCase :List[Any] = od / """test_results.txt""" UpperCamelCase :Tuple = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. UpperCamelCase :Optional[int] = od / F"""{type_path}_results/{trainer.global_step:05d}.txt""" UpperCamelCase :Any = od / F"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=__lowerCamelCase ) generations_file.parent.mkdir(exist_ok=__lowerCamelCase ) with open(__lowerCamelCase , """a+""" ) as writer: for key in sorted(__lowerCamelCase ): if key in ["log", "progress_bar", "preds"]: continue UpperCamelCase :Any = metrics[key] if isinstance(__lowerCamelCase , torch.Tensor ): UpperCamelCase :int = val.item() UpperCamelCase :Union[str, Any] = F"""{key}: {val:.6f}\n""" writer.write(__lowerCamelCase ) if not save_generations: return if "preds" in metrics: UpperCamelCase :Optional[int] = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(__lowerCamelCase ) @rank_zero_only def _A ( self : Any , __lowerCamelCase : Optional[Any] , __lowerCamelCase : str ): try: UpperCamelCase :Any = pl_module.model.model.num_parameters() except AttributeError: UpperCamelCase :List[str] = pl_module.model.num_parameters() UpperCamelCase :List[Any] = count_trainable_parameters(__lowerCamelCase ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1E6, """grad_mp""": n_trainable_pars / 1E6} ) @rank_zero_only def _A ( self : Dict , __lowerCamelCase : pl.Trainer , __lowerCamelCase : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__lowerCamelCase , __lowerCamelCase , """test""" ) @rank_zero_only def _A ( self : Any , __lowerCamelCase : pl.Trainer , __lowerCamelCase : Union[str, Any] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
357
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 1000 ) -> int: """simple docstring""" return sum(e for e in range(3 , __magic_name__ ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(F'''{solution() = }''')
62
0
'''simple docstring''' import os def SCREAMING_SNAKE_CASE__ ( __A = "input.txt" ) -> int: with open(os.path.join(os.path.dirname(__A ) , __A ) ) as input_file: _snake_case = [ [int(__A ) for element in line.split(',' )] for line in input_file.readlines() ] _snake_case = len(__A ) _snake_case = len(matrix[0] ) _snake_case = [[-1 for _ in range(__A )] for _ in range(__A )] for i in range(__A ): _snake_case = matrix[i][0] for j in range(1 , __A ): for i in range(__A ): _snake_case = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , __A ): _snake_case = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): _snake_case = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(F'''{solution() = }''')
42
'''simple docstring''' import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> List[str]: UpperCamelCase = 1.5 UpperCamelCase = int(factor * num_class_images ) UpperCamelCase = ClipClient( url="""https://knn.laion.ai/knn-service""" , indice_name="""laion_400m""" , num_images=__UpperCamelCase , aesthetic_weight=0.1 ) os.makedirs(F"{class_data_dir}/images" , exist_ok=__UpperCamelCase ) if len(list(Path(F"{class_data_dir}/images" ).iterdir() ) ) >= num_class_images: return while True: UpperCamelCase = client.query(text=__UpperCamelCase ) if len(__UpperCamelCase ) >= factor * num_class_images or num_images > 1E4: break else: UpperCamelCase = int(factor * num_images ) UpperCamelCase = ClipClient( url="""https://knn.laion.ai/knn-service""" , indice_name="""laion_400m""" , num_images=__UpperCamelCase , aesthetic_weight=0.1 , ) UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = tqdm(desc="""downloading real regularization images""" , total=__UpperCamelCase ) with open(F"{class_data_dir}/caption.txt" , """w""" ) as fa, open(F"{class_data_dir}/urls.txt" , """w""" ) as fa, open( F"{class_data_dir}/images.txt" , """w""" ) as fa: while total < num_class_images: UpperCamelCase = class_images[count] count += 1 try: UpperCamelCase = requests.get(images["""url"""] ) if img.status_code == 200: UpperCamelCase = Image.open(BytesIO(img.content ) ) with open(F"{class_data_dir}/images/{total}.jpg" , """wb""" ) as f: f.write(img.content ) fa.write(images["""caption"""] + """\n""" ) fa.write(images["""url"""] + """\n""" ) fa.write(F"{class_data_dir}/images/{total}.jpg" + """\n""" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def lowercase__ ( )-> str: UpperCamelCase = argparse.ArgumentParser("""""" , add_help=__UpperCamelCase ) parser.add_argument("""--class_prompt""" , help="""text prompt to retrieve images""" , required=__UpperCamelCase , type=__UpperCamelCase ) parser.add_argument("""--class_data_dir""" , help="""path to save images""" , required=__UpperCamelCase , type=__UpperCamelCase ) parser.add_argument("""--num_class_images""" , help="""number of images to download""" , default=200 , type=__UpperCamelCase ) return parser.parse_args() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
321
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __lowercase: Tuple = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[int]=False , _UpperCamelCase : str=False ) -> Any: '''simple docstring''' UpperCamelCase__ = "backbone." if is_semantic else "" UpperCamelCase__ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'{prefix}blocks.{i}.norm1.weight', F'beit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'{prefix}blocks.{i}.norm1.bias', F'beit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'{prefix}blocks.{i}.attn.proj.weight', F'beit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (F'{prefix}blocks.{i}.attn.proj.bias', F'beit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'{prefix}blocks.{i}.norm2.weight', F'beit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'{prefix}blocks.{i}.norm2.bias', F'beit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc1.weight', F'beit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc1.bias', F'beit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc2.weight', F'beit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc2.bias', F'beit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ (F'{prefix}cls_token', "beit.embeddings.cls_token"), (F'{prefix}patch_embed.proj.weight', "beit.embeddings.patch_embeddings.projection.weight"), (F'{prefix}patch_embed.proj.bias', "beit.embeddings.patch_embeddings.projection.bias"), (F'{prefix}pos_embed', "beit.embeddings.position_embeddings"), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ("mask_token", "beit.embeddings.mask_token"), ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ] ) else: # layernorm + classification head rename_keys.extend( [ ("fc_norm.weight", "beit.pooler.layernorm.weight"), ("fc_norm.bias", "beit.pooler.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Optional[int] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : List[str]=False , _UpperCamelCase : Union[str, Any]=False ) -> Optional[int]: '''simple docstring''' for i in range(config.num_hidden_layers ): UpperCamelCase__ = "backbone." if is_semantic else "" # queries, keys and values UpperCamelCase__ = state_dict.pop(F'{prefix}blocks.{i}.attn.qkv.weight' ) UpperCamelCase__ = state_dict.pop(F'{prefix}blocks.{i}.attn.q_bias' ) UpperCamelCase__ = state_dict.pop(F'{prefix}blocks.{i}.attn.v_bias' ) UpperCamelCase__ = in_proj_weight[ : config.hidden_size, : ] UpperCamelCase__ = q_bias UpperCamelCase__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCamelCase__ = in_proj_weight[ -config.hidden_size :, : ] UpperCamelCase__ = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained UpperCamelCase__ = state_dict.pop(F'{prefix}blocks.{i}.gamma_1' ) UpperCamelCase__ = state_dict.pop(F'{prefix}blocks.{i}.gamma_2' ) UpperCamelCase__ = gamma_a UpperCamelCase__ = gamma_a def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Any , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : List[Any] ) -> Any: '''simple docstring''' UpperCamelCase__ = dct.pop(_UpperCamelCase ) UpperCamelCase__ = val def SCREAMING_SNAKE_CASE__( ) -> Any: '''simple docstring''' UpperCamelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCamelCase__ = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Tuple , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : List[Any]=False ) -> Tuple: '''simple docstring''' UpperCamelCase__ = False if "rvlcdip" in checkpoint_url else True UpperCamelCase__ = BeitConfig(use_absolute_position_embeddings=_UpperCamelCase , use_mask_token=_UpperCamelCase ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: UpperCamelCase__ = 10_24 UpperCamelCase__ = 40_96 UpperCamelCase__ = 24 UpperCamelCase__ = 16 # labels if "rvlcdip" in checkpoint_url: UpperCamelCase__ = 16 UpperCamelCase__ = "huggingface/label-files" UpperCamelCase__ = "rvlcdip-id2label.json" UpperCamelCase__ = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type="dataset" ) , "r" ) ) UpperCamelCase__ = {int(_UpperCamelCase ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys UpperCamelCase__ = torch.hub.load_state_dict_from_url(_UpperCamelCase , map_location="cpu" )["model"] UpperCamelCase__ = create_rename_keys(_UpperCamelCase , has_lm_head=_UpperCamelCase ) for src, dest in rename_keys: rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) read_in_q_k_v(_UpperCamelCase , _UpperCamelCase , has_lm_head=_UpperCamelCase ) # load HuggingFace model UpperCamelCase__ = BeitForMaskedImageModeling(_UpperCamelCase ) if has_lm_head else BeitForImageClassification(_UpperCamelCase ) model.eval() model.load_state_dict(_UpperCamelCase ) # Check outputs on an image UpperCamelCase__ = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=_UpperCamelCase ) UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=_UpperCamelCase , return_tensors="pt" ) UpperCamelCase__ = encoding["pixel_values"] UpperCamelCase__ = model(_UpperCamelCase ) UpperCamelCase__ = outputs.logits # verify logits UpperCamelCase__ = [1, 16] if "rvlcdip" in checkpoint_url else [1, 1_96, 81_92] assert logits.shape == torch.Size(_UpperCamelCase ), "Shape of logits not as expected" Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(_UpperCamelCase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: if has_lm_head: UpperCamelCase__ = "dit-base" if "base" in checkpoint_url else "dit-large" else: UpperCamelCase__ = "dit-base-finetuned-rvlcdip" if "dit-b" in checkpoint_url else "dit-large-finetuned-rvlcdip" image_processor.push_to_hub( repo_path_or_name=Path(_UpperCamelCase , _UpperCamelCase ) , organization="nielsr" , commit_message="Add image processor" , use_temp_dir=_UpperCamelCase , ) model.push_to_hub( repo_path_or_name=Path(_UpperCamelCase , _UpperCamelCase ) , organization="nielsr" , commit_message="Add model" , use_temp_dir=_UpperCamelCase , ) if __name__ == "__main__": __lowercase: Optional[int] = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth", type=str, help="URL to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", ) __lowercase: int = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
31
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__): _lowerCamelCase : str = field(default='audio-classification' , metadata={'include_in_asdict_even_if_is_default': True}) _lowerCamelCase : ClassVar[Features] = Features({'audio': Audio()}) _lowerCamelCase : ClassVar[Features] = Features({'labels': ClassLabel}) _lowerCamelCase : str = "audio" _lowerCamelCase : str = "labels" def lowercase_ ( self : str, a_ : Union[str, Any] ): """simple docstring""" if self.label_column not in features: raise ValueError(f'Column {self.label_column} is not present in features.' ) if not isinstance(features[self.label_column], a_ ): raise ValueError(f'Column {self.label_column} is not a ClassLabel.' ) UpperCamelCase__ = copy.deepcopy(self ) UpperCamelCase__ = self.label_schema.copy() UpperCamelCase__ = features[self.label_column] UpperCamelCase__ = label_schema return task_template @property def lowercase_ ( self : Any ): """simple docstring""" return { self.audio_column: "audio", self.label_column: "labels", }
31
1
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int) -> Optional[int]: '''simple docstring''' if collection == []: return [] # get some information about the collection __UpperCamelCase : Any = len(_lowerCamelCase) __UpperCamelCase : Dict = max(_lowerCamelCase) __UpperCamelCase : List[Any] = min(_lowerCamelCase) # create the counting array __UpperCamelCase : str = coll_max + 1 - coll_min __UpperCamelCase : Tuple = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , _lowerCamelCase): __UpperCamelCase : List[str] = counting_arr[i] + counting_arr[i - 1] # create the output collection __UpperCamelCase : int = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , _lowerCamelCase)): __UpperCamelCase : int = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[int]) -> Union[str, Any]: '''simple docstring''' return "".join([chr(_lowerCamelCase) for i in counting_sort([ord(_lowerCamelCase) for c in string])]) if __name__ == "__main__": # Test string sort assert counting_sort_string('thisisthestring') == "eghhiiinrsssttt" lowercase : List[str] = input('Enter numbers separated by a comma:\n').strip() lowercase : Tuple = [int(item) for item in user_input.split(',')] print(counting_sort(unsorted))
232
class lowerCamelCase__ : '''simple docstring''' def __init__( self :int ) -> Dict: __UpperCamelCase : Union[str, Any] = {} def _lowerCamelCase ( self :str ) -> None: print(self.vertex ) for i in self.vertex: print(a , " -> " , " -> ".join([str(a ) for j in self.vertex[i]] ) ) def _lowerCamelCase ( self :List[Any] , a :int , a :int ) -> None: # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(a ) else: # else make a new vertex __UpperCamelCase : Optional[Any] = [to_vertex] def _lowerCamelCase ( self :Tuple ) -> None: # visited array for storing already visited nodes __UpperCamelCase : Dict = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(a , a ) def _lowerCamelCase ( self :Any , a :int , a :list ) -> None: # mark start vertex as visited __UpperCamelCase : int = True print(a , end=" " ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(a , a ) if __name__ == "__main__": lowercase : Dict = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
232
1
'''simple docstring''' from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def __lowerCamelCase ( _lowercase , _lowercase ) -> Dict: UpperCAmelCase : Dict = [] for part_id in partition_order: UpperCAmelCase : List[str] = df.where(F'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(_lowercase ): expected_row_ids_and_row_dicts.append((F'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ) -> Any: UpperCAmelCase : Dict = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() UpperCAmelCase : Optional[int] = spark.range(1_0_0 ).repartition(1 ) UpperCAmelCase : Dict = Spark(_lowercase ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=1_6 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 5_0 @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ) -> List[Any]: UpperCAmelCase : Optional[int] = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() UpperCAmelCase : Dict = spark.range(1_0 ).repartition(2 ) UpperCAmelCase : Optional[int] = [1, 0] UpperCAmelCase : Any = _generate_iterable_examples(_lowercase , _lowercase ) # Reverse the partitions. UpperCAmelCase : Optional[Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowercase , _lowercase ) for i, (row_id, row_dict) in enumerate(generate_fn() ): UpperCAmelCase , UpperCAmelCase : int = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ) -> Tuple: UpperCAmelCase : Tuple = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() UpperCAmelCase : Optional[int] = spark.range(1_0 ).repartition(1 ) UpperCAmelCase : Optional[Any] = SparkExamplesIterable(_lowercase ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(_lowercase ): assert row_id == F'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ) -> List[str]: UpperCAmelCase : Optional[int] = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() UpperCAmelCase : List[str] = spark.range(3_0 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("""numpy.random.Generator""" ) as generator_mock: UpperCAmelCase : List[str] = lambda _lowercase : x.reverse() UpperCAmelCase : Dict = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowercase , [2, 1, 0] ) UpperCAmelCase : List[str] = SparkExamplesIterable(_lowercase ).shuffle_data_sources(_lowercase ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(_lowercase ): UpperCAmelCase , UpperCAmelCase : int = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ) -> Union[str, Any]: UpperCAmelCase : int = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() UpperCAmelCase : str = spark.range(2_0 ).repartition(4 ) # Partitions 0 and 2 UpperCAmelCase : Any = SparkExamplesIterable(_lowercase ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 UpperCAmelCase : Any = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowercase , [0, 2] ) for i, (row_id, row_dict) in enumerate(_lowercase ): UpperCAmelCase , UpperCAmelCase : List[str] = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 UpperCAmelCase : Dict = SparkExamplesIterable(_lowercase ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 UpperCAmelCase : Dict = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowercase , [1, 3] ) for i, (row_id, row_dict) in enumerate(_lowercase ): UpperCAmelCase , UpperCAmelCase : Optional[Any] = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ) -> Optional[int]: UpperCAmelCase : Dict = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() UpperCAmelCase : Tuple = spark.range(1_0_0 ).repartition(1 ) UpperCAmelCase : Dict = Spark(_lowercase ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_0_0
338
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCamelCase_ : lowercase = MBartConfig lowercase = {} lowercase = 'gelu' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=20 , A=2 , A=1 , A=0 , ) -> Optional[int]: UpperCAmelCase : Optional[int] = parent UpperCAmelCase : Dict = batch_size UpperCAmelCase : Tuple = seq_length UpperCAmelCase : str = is_training UpperCAmelCase : Optional[int] = use_labels UpperCAmelCase : Optional[Any] = vocab_size UpperCAmelCase : Union[str, Any] = hidden_size UpperCAmelCase : Union[str, Any] = num_hidden_layers UpperCAmelCase : List[Any] = num_attention_heads UpperCAmelCase : Optional[int] = intermediate_size UpperCAmelCase : Dict = hidden_dropout_prob UpperCAmelCase : int = attention_probs_dropout_prob UpperCAmelCase : Optional[int] = max_position_embeddings UpperCAmelCase : Optional[Any] = eos_token_id UpperCAmelCase : List[str] = pad_token_id UpperCAmelCase : List[Any] = bos_token_id def _lowercase( self ) -> Union[str, Any]: UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase : List[str] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase : Union[str, Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase : str = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) UpperCAmelCase : List[Any] = prepare_mbart_inputs_dict(A , A , A ) return config, inputs_dict def _lowercase( self , A , A ) -> List[str]: UpperCAmelCase : List[str] = TFMBartModel(config=A ).get_decoder() UpperCAmelCase : int = inputs_dict["""input_ids"""] UpperCAmelCase : str = input_ids[:1, :] UpperCAmelCase : Optional[Any] = inputs_dict["""attention_mask"""][:1, :] UpperCAmelCase : List[str] = inputs_dict["""head_mask"""] UpperCAmelCase : List[Any] = 1 # first forward pass UpperCAmelCase : List[str] = model(A , attention_mask=A , head_mask=A , use_cache=A ) UpperCAmelCase , UpperCAmelCase : Optional[Any] = outputs.to_tuple() UpperCAmelCase : int = past_key_values[1] def __lowerCamelCase ( _lowercase , _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , ) -> List[str]: if attention_mask is None: UpperCAmelCase : Tuple = tf.cast(tf.math.not_equal(_lowercase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase : int = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase : List[Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCamelCase_ ( __magic_name__ , __magic_name__ , unittest.TestCase ): lowercase = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () lowercase = (TFMBartForConditionalGeneration,) if is_tf_available() else () lowercase = ( { 'conversational': TFMBartForConditionalGeneration, 'feature-extraction': TFMBartModel, 'summarization': TFMBartForConditionalGeneration, 'text2text-generation': TFMBartForConditionalGeneration, 'translation': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) lowercase = True lowercase = False lowercase = False def _lowercase( self , A , A , A , A , A ) -> int: if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def _lowercase( self ) -> Optional[Any]: UpperCAmelCase : int = TFMBartModelTester(self ) UpperCAmelCase : Optional[int] = ConfigTester(self , config_class=A ) def _lowercase( self ) -> Optional[int]: self.config_tester.run_common_tests() def _lowercase( self ) -> Dict: UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) @require_sentencepiece @require_tokenizers @require_tf class UpperCamelCase_ ( unittest.TestCase ): lowercase = [ ' UN Chief Says There Is No Military Solution in Syria', ] lowercase = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', ] lowercase = 'facebook/mbart-large-en-ro' @cached_property def _lowercase( self ) -> Any: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _lowercase( self ) -> List[Any]: UpperCAmelCase : Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _lowercase( self , **A ) -> Any: UpperCAmelCase : Optional[int] = self.translate_src_text(**A ) self.assertListEqual(self.expected_text , A ) def _lowercase( self , **A ) -> Optional[Any]: UpperCAmelCase : List[str] = self.tokenizer(self.src_text , **A , return_tensors="""tf""" ) UpperCAmelCase : int = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) UpperCAmelCase : Any = self.tokenizer.batch_decode(A , skip_special_tokens=A ) return generated_words @slow def _lowercase( self ) -> List[Any]: self._assert_generated_batch_equal_expected()
338
1
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : '''simple docstring''' @staticmethod def _lowerCamelCase ( *__lowerCamelCase , **__lowerCamelCase) -> Union[str, Any]: pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase): '''simple docstring''' __SCREAMING_SNAKE_CASE = MODEL_FOR_OBJECT_DETECTION_MAPPING def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> Optional[Any]: _A : Dict = ObjectDetectionPipeline(model=__lowerCamelCase , image_processor=__lowerCamelCase) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase) -> Tuple: _A : Optional[int] = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0) self.assertGreater(len(__lowerCamelCase) , 0) for detected_object in outputs: self.assertEqual( __lowerCamelCase , { "score": ANY(__lowerCamelCase), "label": ANY(__lowerCamelCase), "box": {"xmin": ANY(__lowerCamelCase), "ymin": ANY(__lowerCamelCase), "xmax": ANY(__lowerCamelCase), "ymax": ANY(__lowerCamelCase)}, } , ) import datasets _A : str = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test") _A : str = [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), "http://images.cocodataset.org/val2017/000000039769.jpg", # RGBA dataset[0]["file"], # LA dataset[1]["file"], # L dataset[2]["file"], ] _A : str = object_detector(__lowerCamelCase , threshold=0.0) self.assertEqual(len(__lowerCamelCase) , len(__lowerCamelCase)) for outputs in batch_outputs: self.assertGreater(len(__lowerCamelCase) , 0) for detected_object in outputs: self.assertEqual( __lowerCamelCase , { "score": ANY(__lowerCamelCase), "label": ANY(__lowerCamelCase), "box": {"xmin": ANY(__lowerCamelCase), "ymin": ANY(__lowerCamelCase), "xmax": ANY(__lowerCamelCase), "ymax": ANY(__lowerCamelCase)}, } , ) @require_tf @unittest.skip("Object detection not implemented in TF") def _lowerCamelCase ( self) -> List[Any]: pass @require_torch def _lowerCamelCase ( self) -> List[Any]: _A : Optional[Any] = "hf-internal-testing/tiny-detr-mobilenetsv3" _A : Optional[int] = AutoModelForObjectDetection.from_pretrained(__lowerCamelCase) _A : int = AutoFeatureExtractor.from_pretrained(__lowerCamelCase) _A : Optional[Any] = ObjectDetectionPipeline(model=__lowerCamelCase , feature_extractor=__lowerCamelCase) _A : Union[str, Any] = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 1_5_9, "ymin": 1_2_0, "xmax": 4_8_0, "ymax": 3_5_9}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 1_5_9, "ymin": 1_2_0, "xmax": 4_8_0, "ymax": 3_5_9}}, ] , ) _A : Any = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 1_5_9, "ymin": 1_2_0, "xmax": 4_8_0, "ymax": 3_5_9}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 1_5_9, "ymin": 1_2_0, "xmax": 4_8_0, "ymax": 3_5_9}}, ], [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 1_5_9, "ymin": 1_2_0, "xmax": 4_8_0, "ymax": 3_5_9}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 1_5_9, "ymin": 1_2_0, "xmax": 4_8_0, "ymax": 3_5_9}}, ], ] , ) @require_torch @slow def _lowerCamelCase ( self) -> Optional[Any]: _A : List[Any] = "facebook/detr-resnet-50" _A : Union[str, Any] = AutoModelForObjectDetection.from_pretrained(__lowerCamelCase) _A : Optional[int] = AutoFeatureExtractor.from_pretrained(__lowerCamelCase) _A : Union[str, Any] = ObjectDetectionPipeline(model=__lowerCamelCase , feature_extractor=__lowerCamelCase) _A : Optional[Any] = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg") self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 4_0, "ymin": 7_0, "xmax": 1_7_5, "ymax": 1_1_7}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 3_3_3, "ymin": 7_2, "xmax": 3_6_8, "ymax": 1_8_7}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_3_9, "ymax": 4_7_3}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 1_3, "ymin": 5_2, "xmax": 3_1_4, "ymax": 4_7_0}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 3_4_5, "ymin": 2_3, "xmax": 6_4_0, "ymax": 3_6_8}}, ] , ) _A : Any = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ]) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 4_0, "ymin": 7_0, "xmax": 1_7_5, "ymax": 1_1_7}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 3_3_3, "ymin": 7_2, "xmax": 3_6_8, "ymax": 1_8_7}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_3_9, "ymax": 4_7_3}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 1_3, "ymin": 5_2, "xmax": 3_1_4, "ymax": 4_7_0}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 3_4_5, "ymin": 2_3, "xmax": 6_4_0, "ymax": 3_6_8}}, ], [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 4_0, "ymin": 7_0, "xmax": 1_7_5, "ymax": 1_1_7}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 3_3_3, "ymin": 7_2, "xmax": 3_6_8, "ymax": 1_8_7}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_3_9, "ymax": 4_7_3}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 1_3, "ymin": 5_2, "xmax": 3_1_4, "ymax": 4_7_0}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 3_4_5, "ymin": 2_3, "xmax": 6_4_0, "ymax": 3_6_8}}, ], ] , ) @require_torch @slow def _lowerCamelCase ( self) -> Optional[Any]: _A : int = "facebook/detr-resnet-50" _A : str = pipeline("object-detection" , model=__lowerCamelCase) _A : str = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg") self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 4_0, "ymin": 7_0, "xmax": 1_7_5, "ymax": 1_1_7}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 3_3_3, "ymin": 7_2, "xmax": 3_6_8, "ymax": 1_8_7}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_3_9, "ymax": 4_7_3}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 1_3, "ymin": 5_2, "xmax": 3_1_4, "ymax": 4_7_0}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 3_4_5, "ymin": 2_3, "xmax": 6_4_0, "ymax": 3_6_8}}, ] , ) _A : List[Any] = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ]) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 4_0, "ymin": 7_0, "xmax": 1_7_5, "ymax": 1_1_7}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 3_3_3, "ymin": 7_2, "xmax": 3_6_8, "ymax": 1_8_7}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_3_9, "ymax": 4_7_3}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 1_3, "ymin": 5_2, "xmax": 3_1_4, "ymax": 4_7_0}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 3_4_5, "ymin": 2_3, "xmax": 6_4_0, "ymax": 3_6_8}}, ], [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 4_0, "ymin": 7_0, "xmax": 1_7_5, "ymax": 1_1_7}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 3_3_3, "ymin": 7_2, "xmax": 3_6_8, "ymax": 1_8_7}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_3_9, "ymax": 4_7_3}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 1_3, "ymin": 5_2, "xmax": 3_1_4, "ymax": 4_7_0}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 3_4_5, "ymin": 2_3, "xmax": 6_4_0, "ymax": 3_6_8}}, ], ] , ) @require_torch @slow def _lowerCamelCase ( self) -> int: _A : Any = 0.9_9_8_5 _A : List[str] = "facebook/detr-resnet-50" _A : Dict = pipeline("object-detection" , model=__lowerCamelCase) _A : List[Any] = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=__lowerCamelCase) self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 1_3, "ymin": 5_2, "xmax": 3_1_4, "ymax": 4_7_0}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 3_4_5, "ymin": 2_3, "xmax": 6_4_0, "ymax": 3_6_8}}, ] , ) @require_torch @require_pytesseract @slow def _lowerCamelCase ( self) -> Tuple: _A : str = "Narsil/layoutlmv3-finetuned-funsd" _A : Optional[Any] = 0.9_9_9_3 _A : Any = pipeline("object-detection" , model=__lowerCamelCase , threshold=__lowerCamelCase) _A : List[str] = object_detector( "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png") self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4) , [ {"score": 0.9_9_9_3, "label": "I-ANSWER", "box": {"xmin": 2_9_4, "ymin": 2_5_4, "xmax": 3_4_3, "ymax": 2_6_4}}, {"score": 0.9_9_9_3, "label": "I-ANSWER", "box": {"xmin": 2_9_4, "ymin": 2_5_4, "xmax": 3_4_3, "ymax": 2_6_4}}, ] , )
11
"""simple docstring""" def A ( snake_case__ = 10_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 1, 1 SCREAMING_SNAKE_CASE__ = 2 while True: SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = fa + fa SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = fa, f index += 1 for _ in str(snake_case__ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
165
0
def _a ( a :float , a :int ) -> float: if digit_amount > 0: return round(number - int(a ) , a ) return number - int(a ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
26
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase__ = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
1
'''simple docstring''' import os from pathlib import Path def lowercase ( ): '''simple docstring''' from torch.utils.cpp_extension import load UpperCAmelCase : Optional[Any] = Path(__magic_name__ ).resolve().parent.parent.parent / "kernels" / "deformable_detr" UpperCAmelCase : List[str] = [ root / filename for filename in [ "vision.cpp", os.path.join("cpu" , "ms_deform_attn_cpu.cpp" ), os.path.join("cuda" , "ms_deform_attn_cuda.cu" ), ] ] load( "MultiScaleDeformableAttention" , __magic_name__ , with_cuda=__magic_name__ , extra_include_paths=[str(__magic_name__ )] , extra_cflags=["-DWITH_CUDA=1"] , extra_cuda_cflags=[ "-DCUDA_HAS_FP16=1", "-D__CUDA_NO_HALF_OPERATORS__", "-D__CUDA_NO_HALF_CONVERSIONS__", "-D__CUDA_NO_HALF2_OPERATORS__", ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
311
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() a : Dict = logging.get_logger(__name__) def lowercase ( __magic_name__ ): '''simple docstring''' UpperCAmelCase : List[str] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: UpperCAmelCase : Tuple = 192 UpperCAmelCase : str = 768 UpperCAmelCase : List[Any] = 12 UpperCAmelCase : List[Any] = 3 UpperCAmelCase : List[Any] = [800, 1333] UpperCAmelCase : List[str] = False elif yolos_name == "yolos_s_dWr": UpperCAmelCase : Union[str, Any] = 330 UpperCAmelCase : Union[str, Any] = 14 UpperCAmelCase : Any = 6 UpperCAmelCase : int = 1320 elif "yolos_s" in yolos_name: UpperCAmelCase : Union[str, Any] = 384 UpperCAmelCase : Dict = 1536 UpperCAmelCase : str = 12 UpperCAmelCase : List[str] = 6 elif "yolos_b" in yolos_name: UpperCAmelCase : int = [800, 1344] UpperCAmelCase : Optional[int] = 91 UpperCAmelCase : int = "huggingface/label-files" UpperCAmelCase : Union[str, Any] = "coco-detection-id2label.json" UpperCAmelCase : Optional[Any] = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase : str = {int(__magic_name__ ): v for k, v in idalabel.items()} UpperCAmelCase : str = idalabel UpperCAmelCase : Union[str, Any] = {v: k for k, v in idalabel.items()} return config def lowercase ( __magic_name__ , __magic_name__ , __magic_name__ = False ): '''simple docstring''' for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase : Tuple = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) UpperCAmelCase : List[Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase : str = in_proj_weight[: config.hidden_size, :] UpperCAmelCase : Optional[int] = in_proj_bias[: config.hidden_size] UpperCAmelCase : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase : str = in_proj_weight[-config.hidden_size :, :] UpperCAmelCase : Tuple = in_proj_bias[-config.hidden_size :] def lowercase ( __magic_name__ ): '''simple docstring''' if "backbone" in name: UpperCAmelCase : int = name.replace("backbone" , "vit" ) if "cls_token" in name: UpperCAmelCase : Dict = name.replace("cls_token" , "embeddings.cls_token" ) if "det_token" in name: UpperCAmelCase : int = name.replace("det_token" , "embeddings.detection_tokens" ) if "mid_pos_embed" in name: UpperCAmelCase : Tuple = name.replace("mid_pos_embed" , "encoder.mid_position_embeddings" ) if "pos_embed" in name: UpperCAmelCase : int = name.replace("pos_embed" , "embeddings.position_embeddings" ) if "patch_embed.proj" in name: UpperCAmelCase : str = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "blocks" in name: UpperCAmelCase : Tuple = name.replace("blocks" , "encoder.layer" ) if "attn.proj" in name: UpperCAmelCase : Tuple = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: UpperCAmelCase : Any = name.replace("attn" , "attention.self" ) if "norm1" in name: UpperCAmelCase : int = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: UpperCAmelCase : List[str] = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: UpperCAmelCase : List[str] = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: UpperCAmelCase : Dict = name.replace("mlp.fc2" , "output.dense" ) if "class_embed" in name: UpperCAmelCase : Any = name.replace("class_embed" , "class_labels_classifier" ) if "bbox_embed" in name: UpperCAmelCase : Optional[int] = name.replace("bbox_embed" , "bbox_predictor" ) if "vit.norm" in name: UpperCAmelCase : Tuple = name.replace("vit.norm" , "vit.layernorm" ) return name def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): UpperCAmelCase : Optional[int] = orig_state_dict.pop(__magic_name__ ) if "qkv" in key: UpperCAmelCase : str = key.split("." ) UpperCAmelCase : List[Any] = int(key_split[2] ) UpperCAmelCase : int = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: UpperCAmelCase : Optional[int] = val[:dim, :] UpperCAmelCase : Union[str, Any] = val[ dim : dim * 2, : ] UpperCAmelCase : Any = val[-dim:, :] else: UpperCAmelCase : Tuple = val[:dim] UpperCAmelCase : List[str] = val[dim : dim * 2] UpperCAmelCase : Any = val[-dim:] else: UpperCAmelCase : Union[str, Any] = val return orig_state_dict def lowercase ( ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase : Tuple = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) return im @torch.no_grad() def lowercase ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = False ): '''simple docstring''' UpperCAmelCase : Tuple = get_yolos_config(__magic_name__ ) # load original state_dict UpperCAmelCase : int = torch.load(__magic_name__ , map_location="cpu" )["model"] # load 🤗 model UpperCAmelCase : int = YolosForObjectDetection(__magic_name__ ) model.eval() UpperCAmelCase : Dict = convert_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ ) # Check outputs on an image, prepared by YolosImageProcessor UpperCAmelCase : Dict = 800 if yolos_name != "yolos_ti" else 512 UpperCAmelCase : int = YolosImageProcessor(format="coco_detection" , size=__magic_name__ ) UpperCAmelCase : List[Any] = image_processor(images=prepare_img() , return_tensors="pt" ) UpperCAmelCase : List[str] = model(**__magic_name__ ) UpperCAmelCase , UpperCAmelCase : Optional[int] = outputs.logits, outputs.pred_boxes UpperCAmelCase , UpperCAmelCase : Optional[Any] = None, None if yolos_name == "yolos_ti": UpperCAmelCase : str = torch.tensor( [[-3_9.5_0_2_2, -1_1.9_8_2_0, -1_7.6_8_8_8], [-2_9.9_5_7_4, -9.9_7_6_9, -1_7.7_6_9_1], [-4_2.3_2_8_1, -2_0.7_2_0_0, -3_0.6_2_9_4]] ) UpperCAmelCase : Tuple = torch.tensor( [[0.4_0_2_1, 0.0_8_3_6, 0.7_9_7_9], [0.0_1_8_4, 0.2_6_0_9, 0.0_3_6_4], [0.1_7_8_1, 0.2_0_0_4, 0.2_0_9_5]] ) elif yolos_name == "yolos_s_200_pre": UpperCAmelCase : Union[str, Any] = torch.tensor( [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]] ) UpperCAmelCase : List[str] = torch.tensor( [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]] ) elif yolos_name == "yolos_s_300_pre": UpperCAmelCase : List[str] = torch.tensor( [[-3_6.2_2_2_0, -1_4.4_3_8_5, -2_3.5_4_5_7], [-3_5.6_9_7_0, -1_4.7_5_8_3, -2_1.3_9_3_5], [-3_1.5_9_3_9, -1_3.6_0_4_2, -1_6.8_0_4_9]] ) UpperCAmelCase : Dict = torch.tensor( [[0.7_6_1_4, 0.2_3_1_6, 0.4_7_2_8], [0.7_1_6_8, 0.4_4_9_5, 0.3_8_5_5], [0.4_9_9_6, 0.1_4_6_6, 0.9_9_9_6]] ) elif yolos_name == "yolos_s_dWr": UpperCAmelCase : Dict = torch.tensor( [[-4_2.8_6_6_8, -2_4.1_0_4_9, -4_1.1_6_9_0], [-3_4.7_4_5_6, -1_4.1_2_7_4, -2_4.9_1_9_4], [-3_3.7_8_9_8, -1_2.1_9_4_6, -2_5.6_4_9_5]] ) UpperCAmelCase : List[Any] = torch.tensor( [[0.5_5_8_7, 0.2_7_7_3, 0.0_6_0_5], [0.5_0_0_4, 0.3_0_1_4, 0.9_9_9_4], [0.4_9_9_9, 0.1_5_4_8, 0.9_9_9_4]] ) elif yolos_name == "yolos_base": UpperCAmelCase : str = torch.tensor( [[-4_0.6_0_6_4, -2_4.3_0_8_4, -3_2.6_4_4_7], [-5_5.1_9_9_0, -3_0.7_7_1_9, -3_5.5_8_7_7], [-5_1.4_3_1_1, -3_3.3_5_0_7, -3_5.6_4_6_2]] ) UpperCAmelCase : Union[str, Any] = torch.tensor( [[0.5_5_5_5, 0.2_7_9_4, 0.0_6_5_5], [0.9_0_4_9, 0.2_6_6_4, 0.1_8_9_4], [0.9_1_8_3, 0.1_9_8_4, 0.1_6_3_5]] ) else: raise ValueError(F"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , __magic_name__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , __magic_name__ , atol=1e-4 ) Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) print(F"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__magic_name__ ) if push_to_hub: UpperCAmelCase : int = { "yolos_ti": "yolos-tiny", "yolos_s_200_pre": "yolos-small", "yolos_s_300_pre": "yolos-small-300", "yolos_s_dWr": "yolos-small-dwr", "yolos_base": "yolos-base", } print("Pushing to the hub..." ) UpperCAmelCase : Tuple = model_mapping[yolos_name] image_processor.push_to_hub(__magic_name__ , organization="hustvl" ) model.push_to_hub(__magic_name__ , organization="hustvl" ) if __name__ == "__main__": a : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--yolos_name", default="yolos_s_200_pre", type=str, help=( "Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre'," " 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'." ), ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original state dict (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a : str = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
311
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Any = '''▁''' __UpperCamelCase : int = {'''vocab_file''': '''spiece.model'''} __UpperCamelCase : Tuple = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } __UpperCamelCase : Tuple = { '''google/pegasus-xsum''': 5_1_2, } __UpperCamelCase : Optional[int] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = VOCAB_FILES_NAMES lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] def __init__( self : Tuple ,lowercase_ : str ,lowercase_ : Optional[int]="<pad>" ,lowercase_ : Dict="</s>" ,lowercase_ : str="<unk>" ,lowercase_ : Optional[Any]="<mask_2>" ,lowercase_ : Any="<mask_1>" ,lowercase_ : Optional[int]=None ,lowercase_ : Tuple=1_0_3 ,lowercase_ : Optional[Dict[str, Any]] = None ,**lowercase_ : int ,): lowerCAmelCase__ : Tuple = offset if additional_special_tokens is not None: if not isinstance(lowercase_ ,lowercase_ ): raise TypeError( F'additional_special_tokens should be of type {type(lowercase_ )}, but is' F' {type(lowercase_ )}' ) lowerCAmelCase__ : Dict = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F'<unk_{i}>' for i in range(len(lowercase_ ) ,self.offset - 1 ) ] if len(set(lowercase_ ) ) != len(lowercase_ ): raise ValueError( '''Please make sure that the provided additional_special_tokens do not contain an incorrectly''' F' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) lowerCAmelCase__ : Tuple = additional_special_tokens_extended else: lowerCAmelCase__ : Optional[Any] = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F'<unk_{i}>' for i in range(2 ,self.offset )] lowerCAmelCase__ : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowercase_ ,unk_token=lowercase_ ,mask_token=lowercase_ ,pad_token=lowercase_ ,mask_token_sent=lowercase_ ,offset=lowercase_ ,additional_special_tokens=lowercase_ ,sp_model_kwargs=self.sp_model_kwargs ,**lowercase_ ,) lowerCAmelCase__ : List[Any] = mask_token_sent lowerCAmelCase__ : Any = vocab_file lowerCAmelCase__ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase_ ) # add special tokens to encoder dict lowerCAmelCase__ : Dict[int, str] = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 ,self.offset - 1 )} ) lowerCAmelCase__ : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def __lowerCAmelCase ( self : str ): return len(self.sp_model ) + self.offset def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Optional[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 : Union[str, Any] ): lowerCAmelCase__ : List[str] = self.__dict__.copy() lowerCAmelCase__ : Tuple = None return state def __setstate__( self : int ,lowercase_ : Any ): lowerCAmelCase__ : int = d # for backward compatibility if not hasattr(self ,'''sp_model_kwargs''' ): lowerCAmelCase__ : Union[str, Any] = {} lowerCAmelCase__ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : str ): return self.sp_model.encode(lowercase_ ,out_type=lowercase_ ) def __lowerCAmelCase ( self : int ,lowercase_ : str ): if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] lowerCAmelCase__ : Any = self.sp_model.piece_to_id(lowercase_ ) return sp_id + self.offset def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : int ): if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: lowerCAmelCase__ : Optional[int] = self.sp_model.IdToPiece(index - self.offset ) return token def __lowerCAmelCase ( self : Tuple ,lowercase_ : Dict ): lowerCAmelCase__ : List[Any] = [] lowerCAmelCase__ : int = '''''' 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 lowerCAmelCase__ : Union[str, Any] = [] else: current_sub_tokens.append(lowercase_ ) out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def __lowerCAmelCase ( self : str ,lowercase_ : Union[str, Any]=False ): return 1 def __lowerCAmelCase ( self : int ,lowercase_ : int ): lowerCAmelCase__ : Any = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def __lowerCAmelCase ( self : Optional[int] ,lowercase_ : List ,lowercase_ : Optional[List] = None ,lowercase_ : bool = False ): if already_has_special_tokens: return self._special_token_mask(lowercase_ ) elif token_ids_a is None: return self._special_token_mask(lowercase_ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __lowerCAmelCase ( self : str ,lowercase_ : str ,lowercase_ : str=None ): if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __lowerCAmelCase ( self : Tuple ,lowercase_ : str ,lowercase_ : Optional[str] = None ): if not os.path.isdir(lowercase_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ : 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: lowerCAmelCase__ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
74
"""simple docstring""" __UpperCamelCase : Optional[Any] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def __SCREAMING_SNAKE_CASE ( A_ ): # Make sure the supplied data is a bytes-like object if not isinstance(A_ , A_ ): lowerCAmelCase__ : Dict = f'a bytes-like object is required, not \'{data.__class__.__name__}\'' raise TypeError(A_ ) lowerCAmelCase__ : Any = ''''''.join(bin(A_ )[2:].zfill(8 ) for byte in data ) lowerCAmelCase__ : List[str] = len(A_ ) % 6 != 0 if padding_needed: # The padding that will be added later lowerCAmelCase__ : List[str] = b'''=''' * ((6 - len(A_ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(A_ ) % 6) else: lowerCAmelCase__ : Tuple = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(A_ ) , 6 ) ).encode() + padding ) def __SCREAMING_SNAKE_CASE ( A_ ): # Make sure encoded_data is either a string or a bytes-like object if not isinstance(A_ , A_ ) and not isinstance(A_ , A_ ): lowerCAmelCase__ : str = ( '''argument should be a bytes-like object or ASCII string, ''' f'not \'{encoded_data.__class__.__name__}\'' ) raise TypeError(A_ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(A_ , A_ ): try: lowerCAmelCase__ : Union[str, Any] = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) lowerCAmelCase__ : Union[str, Any] = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(A_ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one lowerCAmelCase__ : List[str] = encoded_data[:-padding] lowerCAmelCase__ : Tuple = ''''''.join( bin(B64_CHARSET.index(A_ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: lowerCAmelCase__ : Any = ''''''.join( bin(B64_CHARSET.index(A_ ) )[2:].zfill(6 ) for char in encoded_data ) lowerCAmelCase__ : List[Any] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(A_ ) , 8 ) ] return bytes(A_ ) if __name__ == "__main__": import doctest doctest.testmod()
74
1
'''simple docstring''' import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def __lowercase ( __lowercase ) -> Optional[Any]: '''simple docstring''' _A = [ "decoder.version", "decoder.output_projection.weight", "_float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(__lowercase , __lowercase ) def __lowercase ( __lowercase ) -> Any: '''simple docstring''' _A , _A = emb.weight.shape _A = nn.Linear(__lowercase , __lowercase , bias=__lowercase ) _A = emb.weight.data return lin_layer def __lowercase ( __lowercase ) -> Optional[int]: '''simple docstring''' _A = torch.load(__lowercase , map_location="cpu" ) _A = Namespace(**checkpoint["cfg"]["model"] ) _A = checkpoint["model"] remove_ignore_keys_(__lowercase ) _A = state_dict["decoder.embed_tokens.weight"].shape[0] _A = {key.replace("decoder" , "model" ): val for key, val in state_dict.items()} _A = XGLMConfig( vocab_size=__lowercase , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="gelu" , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) _A = XGLMForCausalLM(__lowercase ) _A = model.load_state_dict(__lowercase , strict=__lowercase ) print(__lowercase ) _A = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument('''fairseq_path''', type=str, help='''path to a model.pt on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
79
"""simple docstring""" def lowercase ( A_ , A_ )-> float: '''simple docstring''' if mass < 0: raise ValueError("The mass of a body cannot be negative" ) return 0.5 * mass * abs(A_ ) * abs(A_ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
40
0
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, ) lowerCamelCase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ """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 lowerCamelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
352
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor lowerCamelCase_ = logging.get_logger(__name__) class a_ ( a_ ): '''simple docstring''' def __init__( self , *lowercase_ , **lowercase_ ) -> None: '''simple docstring''' warnings.warn( 'The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PoolFormerImageProcessor instead.' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_ )
14
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''xlm-mlm-en-2048''': '''https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json''', '''xlm-mlm-ende-1024''': '''https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json''', '''xlm-mlm-enfr-1024''': '''https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json''', '''xlm-mlm-enro-1024''': '''https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json''', '''xlm-mlm-tlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json''', '''xlm-mlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json''', '''xlm-clm-enfr-1024''': '''https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json''', '''xlm-clm-ende-1024''': '''https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json''', '''xlm-mlm-17-1280''': '''https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json''', '''xlm-mlm-100-1280''': '''https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json''', } class _snake_case ( a__ ): snake_case__ = "xlm" snake_case__ = { "hidden_size": "emb_dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", "n_words": "vocab_size", # For backward compatibility } def __init__( self : str , UpperCAmelCase : str=30145 , UpperCAmelCase : Optional[Any]=2048 , UpperCAmelCase : Tuple=12 , UpperCAmelCase : List[Any]=16 , UpperCAmelCase : Any=0.1 , UpperCAmelCase : Any=0.1 , UpperCAmelCase : Union[str, Any]=True , UpperCAmelCase : List[str]=False , UpperCAmelCase : int=False , UpperCAmelCase : List[str]=False , UpperCAmelCase : Dict=1 , UpperCAmelCase : List[Any]=True , UpperCAmelCase : int=512 , UpperCAmelCase : Optional[Any]=2048**-0.5 , UpperCAmelCase : Union[str, Any]=1E-12 , UpperCAmelCase : Tuple=0.0_2 , UpperCAmelCase : Dict=0 , UpperCAmelCase : List[Any]=1 , UpperCAmelCase : List[Any]=2 , UpperCAmelCase : Optional[Any]=3 , UpperCAmelCase : str=5 , UpperCAmelCase : List[Any]=True , UpperCAmelCase : List[str]="first" , UpperCAmelCase : int=True , UpperCAmelCase : List[Any]=None , UpperCAmelCase : str=True , UpperCAmelCase : Any=0.1 , UpperCAmelCase : List[str]=5 , UpperCAmelCase : Union[str, Any]=5 , UpperCAmelCase : str=0 , UpperCAmelCase : Union[str, Any]=0 , UpperCAmelCase : int=2 , UpperCAmelCase : Dict=0 , **UpperCAmelCase : int , ): __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Union[str, Any] = emb_dim __lowerCamelCase : Dict = n_layers __lowerCamelCase : Dict = n_heads __lowerCamelCase : Optional[int] = dropout __lowerCamelCase : str = attention_dropout __lowerCamelCase : Tuple = gelu_activation __lowerCamelCase : Any = sinusoidal_embeddings __lowerCamelCase : List[Any] = causal __lowerCamelCase : List[Any] = asm __lowerCamelCase : Tuple = n_langs __lowerCamelCase : Any = use_lang_emb __lowerCamelCase : Union[str, Any] = layer_norm_eps __lowerCamelCase : int = bos_index __lowerCamelCase : Dict = eos_index __lowerCamelCase : Optional[int] = pad_index __lowerCamelCase : Dict = unk_index __lowerCamelCase : str = mask_index __lowerCamelCase : Tuple = is_encoder __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Union[str, Any] = embed_init_std __lowerCamelCase : List[str] = init_std __lowerCamelCase : Dict = summary_type __lowerCamelCase : int = summary_use_proj __lowerCamelCase : Optional[int] = summary_activation __lowerCamelCase : List[Any] = summary_proj_to_labels __lowerCamelCase : Any = summary_first_dropout __lowerCamelCase : int = start_n_top __lowerCamelCase : str = end_n_top __lowerCamelCase : int = mask_token_id __lowerCamelCase : int = lang_id if "n_words" in kwargs: __lowerCamelCase : int = kwargs["n_words"] super().__init__(pad_token_id=UpperCAmelCase , bos_token_id=UpperCAmelCase , **UpperCAmelCase ) class _snake_case ( a__ ): @property def lowerCamelCase__ ( self : Any ): if self.task == "multiple-choice": __lowerCamelCase : Any = {0: "batch", 1: "choice", 2: "sequence"} else: __lowerCamelCase : Tuple = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
135
"""simple docstring""" import math import random def lowercase_ ( _lowerCamelCase: float , _lowerCamelCase: bool = False ) -> float: '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __A = 0.02 def lowercase_ ( _lowerCamelCase: int , _lowerCamelCase: int ) -> float: '''simple docstring''' __lowerCamelCase : Tuple = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(_lowerCamelCase ): # Forward propagation __lowerCamelCase : List[Any] = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __lowerCamelCase : Any = (expected / 100) - layer_a # Error delta __lowerCamelCase : Dict = layer_1_error * sigmoid_function(_lowerCamelCase , _lowerCamelCase ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() __A = int(input('''Expected value: ''')) __A = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
135
1
'''simple docstring''' import re import string import numpy as np import datasets lowerCAmelCase : List[str] = """ Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. """ lowerCAmelCase : Any = """ Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results[\"exact_match\"], 1)) 25.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True) >>> print(round(results[\"exact_match\"], 1)) 50.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True) >>> print(round(results[\"exact_match\"], 1)) 75.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results[\"exact_match\"], 1)) 100.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"] >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results[\"exact_match\"], 1)) 33.3 """ lowerCAmelCase : Any = """ """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): """simple docstring""" def a ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , reference_urls=[] , ) def a ( self , snake_case__ , snake_case__ , snake_case__=None , snake_case__=False , snake_case__=False , snake_case__=False , ): '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: _lowerCAmelCase : Optional[Any] = np.array([re.sub(snake_case__ , '' , snake_case__ ) for x in predictions] ) _lowerCAmelCase : Tuple = np.array([re.sub(snake_case__ , '' , snake_case__ ) for x in references] ) else: _lowerCAmelCase : str = np.asarray(snake_case__ ) _lowerCAmelCase : Any = np.asarray(snake_case__ ) if ignore_case: _lowerCAmelCase : Dict = np.char.lower(snake_case__ ) _lowerCAmelCase : List[Any] = np.char.lower(snake_case__ ) if ignore_punctuation: _lowerCAmelCase : Optional[Any] = string.punctuation.maketrans('' , '' , string.punctuation ) _lowerCAmelCase : Dict = np.char.translate(snake_case__ , table=snake_case__ ) _lowerCAmelCase : Tuple = np.char.translate(snake_case__ , table=snake_case__ ) if ignore_numbers: _lowerCAmelCase : Optional[Any] = string.digits.maketrans('' , '' , string.digits ) _lowerCAmelCase : Dict = np.char.translate(snake_case__ , table=snake_case__ ) _lowerCAmelCase : int = np.char.translate(snake_case__ , table=snake_case__ ) _lowerCAmelCase : int = predictions == references return {"exact_match": np.mean(snake_case__ ) * 100}
25
'''simple docstring''' lowerCAmelCase : Union[str, Any] = 0 # The first color of the flag. lowerCAmelCase : Optional[int] = 1 # The second color of the flag. lowerCAmelCase : int = 2 # The third color of the flag. lowerCAmelCase : Any = (red, white, blue) def lowercase (_A ): """simple docstring""" if not sequence: return [] if len(_A ) == 1: return list(_A ) _lowerCAmelCase : Optional[int] = 0 _lowerCAmelCase : List[str] = len(_A ) - 1 _lowerCAmelCase : Optional[Any] = 0 while mid <= high: if sequence[mid] == colors[0]: _lowerCAmelCase , _lowerCAmelCase : Tuple = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: _lowerCAmelCase , _lowerCAmelCase : Tuple = sequence[high], sequence[mid] high -= 1 else: _lowerCAmelCase : Optional[int] = f'The elements inside the sequence must contains only {colors} values' raise ValueError(_A ) return sequence if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase : str = input("""Enter numbers separated by commas:\n""").strip() lowerCAmelCase : Dict = [int(item.strip()) for item in user_input.split(""",""")] print(F'''{dutch_national_flag_sort(unsorted)}''')
25
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : Tuple ) -> List[str]: '''simple docstring''' if collection == []: return [] # get some information about the collection UpperCAmelCase_ = len(snake_case_ ) UpperCAmelCase_ = max(snake_case_ ) UpperCAmelCase_ = min(snake_case_ ) # create the counting array UpperCAmelCase_ = coll_max + 1 - coll_min UpperCAmelCase_ = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , snake_case_ ): UpperCAmelCase_ = counting_arr[i] + counting_arr[i - 1] # create the output collection UpperCAmelCase_ = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , snake_case_ ) ): UpperCAmelCase_ = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' return "".join([chr(snake_case_ ) for i in counting_sort([ord(snake_case_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('thisisthestring') == "eghhiiinrsssttt" SCREAMING_SNAKE_CASE_: List[Any] =input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE_: Union[str, Any] =[int(item) for item in user_input.split(',')] print(counting_sort(unsorted))
1
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "contact@muhammadumerfarooq.me" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
0
import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class a__ ( UpperCamelCase__ , unittest.TestCase ): a : int = """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline""" def lowerCAmelCase_ ( self , A=0 ) -> List[Any]: '''simple docstring''' a = np.random.RandomState(A ) a = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def lowerCAmelCase_ ( self ) -> List[str]: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = pipe(**A ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) a = np.array([0.6_5_0_7_2, 0.5_8_4_9_2, 0.4_8_2_1_9, 0.5_5_5_2_1, 0.5_3_1_8_0, 0.5_5_9_3_9, 0.5_0_6_9_7, 0.3_9_8_0_0, 0.4_6_4_5_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self ) -> Union[str, Any]: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) a = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=A ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = pipe(**A ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) a = np.array([0.6_5_8_6_3, 0.5_9_4_2_5, 0.4_9_3_2_6, 0.5_6_3_1_3, 0.5_3_8_7_5, 0.5_6_6_2_7, 0.5_1_0_6_5, 0.3_9_7_7_7, 0.4_6_3_3_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self ) -> Any: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) a = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = pipe(**A ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) a = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self ) -> Tuple: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) a = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = pipe(**A ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) a = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self ) -> Any: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) a = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = pipe(**A ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) a = np.array([0.5_3_8_1_7, 0.6_0_8_1_2, 0.4_7_3_8_4, 0.4_9_5_3_0, 0.5_1_8_9_4, 0.4_9_8_1_4, 0.4_7_9_8_4, 0.3_8_9_5_8, 0.4_4_2_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self ) -> str: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) a = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = pipe(**A ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) a = np.array([0.5_3_8_9_5, 0.6_0_8_0_8, 0.4_7_9_3_3, 0.4_9_6_0_8, 0.5_1_8_8_6, 0.4_9_9_5_0, 0.4_8_0_5_3, 0.3_8_9_5_7, 0.4_4_2_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self ) -> Dict: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = 3 * [inputs["prompt"]] # forward a = pipe(**A ) a = output.images[0, -3:, -3:, -1] a = self.get_dummy_inputs() a = 3 * [inputs.pop("prompt" )] a = pipe.tokenizer( A , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=A , return_tensors="np" , ) a = text_inputs["input_ids"] a = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] a = prompt_embeds # forward a = pipe(**A ) a = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 def lowerCAmelCase_ ( self ) -> str: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=A ) a = self.get_dummy_inputs() a = 3 * ["this is a negative prompt"] a = negative_prompt a = 3 * [inputs["prompt"]] # forward a = pipe(**A ) a = output.images[0, -3:, -3:, -1] a = self.get_dummy_inputs() a = 3 * [inputs.pop("prompt" )] a = [] for p in [prompt, negative_prompt]: a = pipe.tokenizer( A , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=A , return_tensors="np" , ) a = text_inputs["input_ids"] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) a , a = embeds # forward a = pipe(**A ) a = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @nightly @require_onnxruntime @require_torch_gpu class a__ ( unittest.TestCase ): @property def lowerCAmelCase_ ( self ) -> Tuple: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCAmelCase_ ( self ) -> str: '''simple docstring''' a = ort.SessionOptions() a = False return options def lowerCAmelCase_ ( self ) -> List[str]: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=A , feature_extractor=A , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=A ) a = "A painting of a squirrel eating a burger" np.random.seed(0 ) a = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="np" ) a = output.images a = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) a = np.array([0.0_4_5_2, 0.0_3_9_0, 0.0_0_8_7, 0.0_3_5_0, 0.0_6_1_7, 0.0_3_6_4, 0.0_5_4_4, 0.0_5_2_3, 0.0_7_2_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCAmelCase_ ( self ) -> str: '''simple docstring''' a = DDIMScheduler.from_pretrained( "runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" ) a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=A , safety_checker=A , feature_extractor=A , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=A ) a = "open neural network exchange" a = np.random.RandomState(0 ) a = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=A , output_type="np" ) a = output.images a = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) a = np.array([0.2_8_6_7, 0.1_9_7_4, 0.1_4_8_1, 0.7_2_9_4, 0.7_2_5_1, 0.6_6_6_7, 0.4_1_9_4, 0.5_6_4_2, 0.6_4_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCAmelCase_ ( self ) -> Dict: '''simple docstring''' a = LMSDiscreteScheduler.from_pretrained( "runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" ) a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=A , safety_checker=A , feature_extractor=A , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=A ) a = "open neural network exchange" a = np.random.RandomState(0 ) a = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=A , output_type="np" ) a = output.images a = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) a = np.array([0.2_3_0_6, 0.1_9_5_9, 0.1_5_9_3, 0.6_5_4_9, 0.6_3_9_4, 0.5_4_0_8, 0.5_0_6_5, 0.6_0_1_0, 0.6_1_6_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCAmelCase_ ( self ) -> str: '''simple docstring''' a = 0 def test_callback_fn(A , A , A ) -> None: a = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) a = latents[0, -3:, -3:, -1] a = np.array( [-0.6_7_7_2, -0.3_8_3_5, -1.2_4_5_6, 0.1_9_0_5, -1.0_9_7_4, 0.6_9_6_7, -1.9_3_5_3, 0.0_1_7_8, 1.0_1_6_7] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) a = latents[0, -3:, -3:, -1] a = np.array( [-0.3_3_5_1, 0.2_2_4_1, -0.1_8_3_7, -0.2_3_2_5, -0.6_5_7_7, 0.3_3_9_3, -0.0_2_4_1, 0.5_8_9_9, 1.3_8_7_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 a = False a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=A , feature_extractor=A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=A ) a = "Andromeda galaxy in a bottle" a = np.random.RandomState(0 ) pipe( prompt=A , num_inference_steps=5 , guidance_scale=7.5 , generator=A , callback=A , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def lowerCAmelCase_ ( self ) -> int: '''simple docstring''' a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=A , feature_extractor=A , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(A , A ) assert pipe.safety_checker is None a = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(A ) a = OnnxStableDiffusionPipeline.from_pretrained(A ) # sanity check that the pipeline still works assert pipe.safety_checker is None a = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None
180
lowercase__ : str = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowercase__ : Any = [{"type": "code", "content": INSTALL_CONTENT}] lowercase__ : Any = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
180
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> List[str]: """simple docstring""" class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = metric_id class __lowerCAmelCase : lowerCamelCase_ : Optional[Any] = [MetricMock(_a ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def lowerCamelCase (self ) -> str: '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" if "tmp_path" in args: snake_case_ : Any = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(lowerCamelCase__ , match='''https://huggingface.co/docs/evaluate''' ): func(*lowerCamelCase__ )
279
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A : def __init__(self : Dict , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any]=1_3 , __UpperCAmelCase : Union[str, Any]=7 , __UpperCAmelCase : Union[str, Any]=False , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : int=True , __UpperCAmelCase : Any=3_3 , __UpperCAmelCase : List[Any]=3_2 , __UpperCAmelCase : Union[str, Any]=5 , __UpperCAmelCase : Optional[int]=4 , __UpperCAmelCase : int=3_7 , __UpperCAmelCase : Any="gelu" , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : Optional[int]=5_1_2 , __UpperCAmelCase : int=1_6 , __UpperCAmelCase : List[Any]=2 , __UpperCAmelCase : int=0.02 , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : List[str]=4 , __UpperCAmelCase : Dict=None , ) -> Dict: """simple docstring""" UpperCAmelCase__ = parent UpperCAmelCase__ = batch_size UpperCAmelCase__ = seq_length UpperCAmelCase__ = is_training UpperCAmelCase__ = use_input_mask UpperCAmelCase__ = use_token_type_ids UpperCAmelCase__ = use_labels UpperCAmelCase__ = vocab_size UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = type_vocab_size UpperCAmelCase__ = type_sequence_label_size UpperCAmelCase__ = initializer_range UpperCAmelCase__ = num_labels UpperCAmelCase__ = num_choices UpperCAmelCase__ = scope def lowercase_ (self : Tuple ) -> str: """simple docstring""" UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase__ = None if self.use_input_mask: UpperCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None if self.use_labels: UpperCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ (self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowercase_ (self : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str] ) -> List[str]: """simple docstring""" UpperCAmelCase__ = EsmModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase ) UpperCAmelCase__ = model(__UpperCAmelCase ) UpperCAmelCase__ = model(__UpperCAmelCase ) 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 lowercase_ (self : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Dict ) -> List[str]: """simple docstring""" UpperCAmelCase__ = EsmForMaskedLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ (self : Dict , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = EsmForTokenClassification(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ (self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.prepare_config_and_inputs() ( ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ) = config_and_inputs UpperCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): __UpperCAmelCase : str = False __UpperCAmelCase : Dict = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : List[str] = () __UpperCAmelCase : List[str] = ( { 'feature-extraction': EsmModel, 'fill-mask': EsmForMaskedLM, 'text-classification': EsmForSequenceClassification, 'token-classification': EsmForTokenClassification, 'zero-shot': EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : str = True def lowercase_ (self : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = EsmModelTester(self ) UpperCAmelCase__ = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=3_7 ) def lowercase_ (self : int ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def lowercase_ (self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def lowercase_ (self : List[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase__ = type self.model_tester.create_and_check_model(*__UpperCAmelCase ) def lowercase_ (self : str ) -> int: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase ) def lowercase_ (self : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase ) @slow def lowercase_ (self : List[Any] ) -> str: """simple docstring""" for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ = EsmModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def lowercase_ (self : Union[str, Any] ) -> List[str]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs()[0] UpperCAmelCase__ = EsmEmbeddings(config=__UpperCAmelCase ) UpperCAmelCase__ = torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) UpperCAmelCase__ = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) UpperCAmelCase__ = create_position_ids_from_input_ids(__UpperCAmelCase , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(__UpperCAmelCase , __UpperCAmelCase ) ) ) def lowercase_ (self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs()[0] UpperCAmelCase__ = EsmEmbeddings(config=__UpperCAmelCase ) UpperCAmelCase__ = torch.empty(2 , 4 , 3_0 ) UpperCAmelCase__ = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] UpperCAmelCase__ = torch.as_tensor([expected_single_positions, expected_single_positions] ) UpperCAmelCase__ = embeddings.create_position_ids_from_inputs_embeds(__UpperCAmelCase ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(__UpperCAmelCase , __UpperCAmelCase ) ) ) @unittest.skip("Esm does not support embedding resizing" ) def lowercase_ (self : Tuple ) -> Any: """simple docstring""" pass @unittest.skip("Esm does not support embedding resizing" ) def lowercase_ (self : List[Any] ) -> List[Any]: """simple docstring""" pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def lowercase_ (self : Optional[Any] ) -> List[Any]: """simple docstring""" pass @require_torch class A ( UpperCAmelCase_ ): @slow def lowercase_ (self : str ) -> int: """simple docstring""" with torch.no_grad(): UpperCAmelCase__ = EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D" ) model.eval() UpperCAmelCase__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) UpperCAmelCase__ = model(__UpperCAmelCase )[0] UpperCAmelCase__ = 3_3 UpperCAmelCase__ = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) UpperCAmelCase__ = torch.tensor( [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def lowercase_ (self : Dict ) -> List[Any]: """simple docstring""" with torch.no_grad(): UpperCAmelCase__ = EsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D" ) model.eval() UpperCAmelCase__ = torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) UpperCAmelCase__ = model(__UpperCAmelCase )[0] # compare the actual values for a slice. UpperCAmelCase__ = torch.tensor( [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) )
143
# 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 .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def lowerCAmelCase_ ( __A=None ) -> str: '''simple docstring''' UpperCAmelCase__ = argparse.ArgumentParser(add_help=__A, allow_abbrev=__A ) # The main config parser UpperCAmelCase__ = config_command_parser(__A ) # The subparser to add commands to UpperCAmelCase__ = config_parser.add_subparsers(title="subcommands", dest="subcommand" ) # Then add other parsers with the parent parser default_command_parser(__A, parents=[parent_parser] ) update_command_parser(__A, parents=[parent_parser] ) return config_parser def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' UpperCAmelCase__ = get_config_parser() UpperCAmelCase__ = config_parser.parse_args() if not hasattr(__A, "func" ): config_parser.print_help() exit(1 ) # Run args.func(__A ) if __name__ == "__main__": main()
143
1
'''simple docstring''' import math import os import sys def UpperCamelCase_ ( _UpperCAmelCase : str ) -> str: """simple docstring""" _UpperCAmelCase : List[str] = "" try: with open(_UpperCAmelCase , "rb" ) as binary_file: _UpperCAmelCase : Tuple = binary_file.read() for dat in data: _UpperCAmelCase : int = F"""{dat:08b}""" result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def UpperCamelCase_ ( _UpperCAmelCase : dict[str, str] , _UpperCAmelCase : str , _UpperCAmelCase : int , _UpperCAmelCase : str ) -> None: """simple docstring""" lexicon.pop(_UpperCAmelCase ) _UpperCAmelCase : int = last_match_id if math.loga(_UpperCAmelCase ).is_integer(): for curr_key in lexicon: _UpperCAmelCase : Optional[int] = "0" + lexicon[curr_key] _UpperCAmelCase : Union[str, Any] = bin(_UpperCAmelCase )[2:] def UpperCamelCase_ ( _UpperCAmelCase : str ) -> str: """simple docstring""" _UpperCAmelCase : List[Any] = {"0": "0", "1": "1"} _UpperCAmelCase , _UpperCAmelCase : str = "", "" _UpperCAmelCase : List[Any] = len(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue _UpperCAmelCase : Union[str, Any] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) index += 1 _UpperCAmelCase : int = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": _UpperCAmelCase : Any = lexicon[curr_string] result += last_match_id return result def UpperCamelCase_ ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> str: """simple docstring""" _UpperCAmelCase : List[Any] = os.path.getsize(_UpperCAmelCase ) _UpperCAmelCase : Tuple = bin(_UpperCAmelCase )[2:] _UpperCAmelCase : int = len(_UpperCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def UpperCamelCase_ ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> None: """simple docstring""" _UpperCAmelCase : List[str] = 8 try: with open(_UpperCAmelCase , "wb" ) as opened_file: _UpperCAmelCase : Optional[int] = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase ) , _UpperCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def UpperCamelCase_ ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> None: """simple docstring""" _UpperCAmelCase : int = read_file_binary(_UpperCAmelCase ) _UpperCAmelCase : Tuple = compress_data(_UpperCAmelCase ) _UpperCAmelCase : Optional[Any] = add_file_length(_UpperCAmelCase , _UpperCAmelCase ) write_file_binary(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
31
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase_ : '''simple docstring''' def __init__( self : List[Any] , A : Dict , A : Optional[Any]=13 , A : Optional[Any]=7 , A : Union[str, Any]=True , A : Optional[Any]=True , A : int=False , A : str=True , A : Optional[Any]=99 , A : Union[str, Any]=32 , A : int=5 , A : Tuple=4 , A : Union[str, Any]=37 , A : Dict="gelu" , A : Union[str, Any]=0.1 , A : str=0.1 , A : Union[str, Any]=512 , A : int=16 , A : List[str]=2 , A : Tuple=0.02 , A : int=3 , A : List[str]=4 , A : str=None , ): _UpperCAmelCase : List[Any] = parent _UpperCAmelCase : Any = batch_size _UpperCAmelCase : int = seq_length _UpperCAmelCase : Union[str, Any] = is_training _UpperCAmelCase : Any = use_input_mask _UpperCAmelCase : Optional[Any] = use_token_type_ids _UpperCAmelCase : str = use_labels _UpperCAmelCase : Union[str, Any] = vocab_size _UpperCAmelCase : Tuple = hidden_size _UpperCAmelCase : Union[str, Any] = num_hidden_layers _UpperCAmelCase : Optional[Any] = num_attention_heads _UpperCAmelCase : Union[str, Any] = intermediate_size _UpperCAmelCase : Union[str, Any] = hidden_act _UpperCAmelCase : List[Any] = hidden_dropout_prob _UpperCAmelCase : List[Any] = attention_probs_dropout_prob _UpperCAmelCase : Optional[int] = max_position_embeddings _UpperCAmelCase : str = type_vocab_size _UpperCAmelCase : str = type_sequence_label_size _UpperCAmelCase : int = initializer_range _UpperCAmelCase : Optional[Any] = num_labels _UpperCAmelCase : List[str] = num_choices _UpperCAmelCase : List[str] = scope def _A ( self : Optional[int] ): _UpperCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase : Union[str, Any] = None if self.use_input_mask: _UpperCAmelCase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCAmelCase : Any = None if self.use_token_type_ids: _UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCAmelCase : Optional[int] = None _UpperCAmelCase : Any = None _UpperCAmelCase : Optional[int] = None if self.use_labels: _UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCAmelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _UpperCAmelCase : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _A ( self : Dict ): return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A , initializer_range=self.initializer_range , ) def _A ( self : int , A : List[Any] , A : Any , A : int , A : Union[str, Any] , A : Dict , A : List[Any] , A : Dict ): _UpperCAmelCase : List[str] = BioGptModel(config=A ) model.to(A ) model.eval() _UpperCAmelCase : Tuple = model(A , attention_mask=A ) _UpperCAmelCase : int = model(A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : List[Any] , A : str , A : List[Any] , A : Dict , A : List[Any] , A : List[str] , A : Union[str, Any] , A : int , A : List[str] , A : Dict , ): _UpperCAmelCase : Optional[int] = BioGptForCausalLM(config=A ) model.to(A ) model.eval() _UpperCAmelCase : Optional[int] = model(A , attention_mask=A , token_type_ids=A , labels=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[Any] , A : str , A : str , A : str , A : Any , A : List[str] , *A : Optional[int] ): _UpperCAmelCase : str = BioGptModel(config=A ) model.to(A ) model.eval() # create attention mask _UpperCAmelCase : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=A ) _UpperCAmelCase : Optional[int] = self.seq_length // 2 _UpperCAmelCase : List[Any] = 0 # first forward pass _UpperCAmelCase , _UpperCAmelCase : List[str] = model(A , attention_mask=A ).to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCAmelCase : List[str] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids _UpperCAmelCase : List[str] = ids_tensor((1,) , A ).item() + 1 _UpperCAmelCase : str = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) _UpperCAmelCase : Any = random_other_next_tokens # append to next input_ids and attn_mask _UpperCAmelCase : List[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) _UpperCAmelCase : Optional[int] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=A )] , dim=1 , ) # get two different outputs _UpperCAmelCase : List[Any] = model(A , attention_mask=A )["last_hidden_state"] _UpperCAmelCase : Optional[Any] = model(A , past_key_values=A , attention_mask=A )["last_hidden_state"] # select random slice _UpperCAmelCase : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() _UpperCAmelCase : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() _UpperCAmelCase : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A , A , atol=1E-3 ) ) def _A ( self : int , A : Dict , A : str , A : Dict , A : Union[str, Any] , A : Any , *A : Union[str, Any] ): _UpperCAmelCase : Optional[Any] = BioGptModel(config=A ).to(A ).eval() _UpperCAmelCase : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=A ) # first forward pass _UpperCAmelCase : Union[str, Any] = model(A , attention_mask=A , use_cache=A ) _UpperCAmelCase , _UpperCAmelCase : Dict = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids _UpperCAmelCase : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCAmelCase : Any = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and _UpperCAmelCase : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) _UpperCAmelCase : Dict = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) _UpperCAmelCase : Any = model(A , attention_mask=A )["last_hidden_state"] _UpperCAmelCase : Dict = model(A , attention_mask=A , past_key_values=A )[ "last_hidden_state" ] # select random slice _UpperCAmelCase : Dict = ids_tensor((1,) , output_from_past.shape[-1] ).item() _UpperCAmelCase : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() _UpperCAmelCase : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A , A , atol=1E-3 ) ) def _A ( self : Optional[Any] , A : Tuple , A : List[str] , A : Tuple , A : Dict , A : List[Any] , *A : Tuple , A : List[str]=False ): _UpperCAmelCase : Optional[int] = BioGptForCausalLM(A ) model.to(A ) if gradient_checkpointing: model.gradient_checkpointing_enable() _UpperCAmelCase : Union[str, Any] = model(A , labels=A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _A ( self : Optional[Any] , A : Any , *A : Optional[Any] ): _UpperCAmelCase : Tuple = BioGptModel(A ) _UpperCAmelCase : int = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _A ( self : Optional[int] , A : Dict , A : Tuple , A : Optional[int] , A : int , A : List[str] , *A : Dict ): _UpperCAmelCase : Any = self.num_labels _UpperCAmelCase : Any = BioGptForTokenClassification(A ) model.to(A ) model.eval() _UpperCAmelCase : Optional[int] = model(A , attention_mask=A , token_type_ids=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : int ): _UpperCAmelCase : Dict = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) : List[str] = config_and_inputs _UpperCAmelCase : Optional[int] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class lowerCamelCase_ (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase: List[str] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __UpperCamelCase: List[str] = (BioGptForCausalLM,) if is_torch_available() else () __UpperCamelCase: str = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase: Union[str, Any] = False def _A ( self : Optional[Any] ): _UpperCAmelCase : List[Any] = BioGptModelTester(self ) _UpperCAmelCase : str = ConfigTester(self , config_class=A , hidden_size=37 ) def _A ( self : Union[str, Any] ): self.config_tester.run_common_tests() def _A ( self : Any ): _UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def _A ( self : Any ): _UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase : Tuple = type self.model_tester.create_and_check_model(*A ) def _A ( self : int ): _UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*A ) def _A ( self : Union[str, Any] ): _UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*A , gradient_checkpointing=A ) def _A ( self : Union[str, Any] ): _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*A ) def _A ( self : Dict ): _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*A ) def _A ( self : Dict ): _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*A ) @slow def _A ( self : List[str] ): _UpperCAmelCase : Optional[Any] = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(A ) _UpperCAmelCase : Tuple = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) _UpperCAmelCase : str = "left" # Define PAD Token = EOS Token = 50256 _UpperCAmelCase : Any = tokenizer.eos_token _UpperCAmelCase : int = model.config.eos_token_id # use different length sentences to test batching _UpperCAmelCase : Any = [ "Hello, my dog is a little", "Today, I", ] _UpperCAmelCase : Tuple = tokenizer(A , return_tensors="pt" , padding=A ) _UpperCAmelCase : Optional[Any] = inputs["input_ids"].to(A ) _UpperCAmelCase : Any = model.generate( input_ids=A , attention_mask=inputs["attention_mask"].to(A ) , ) _UpperCAmelCase : int = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(A ) _UpperCAmelCase : List[Any] = model.generate(input_ids=A ) _UpperCAmelCase : List[Any] = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() _UpperCAmelCase : int = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(A ) _UpperCAmelCase : int = model.generate(input_ids=A , max_length=model.config.max_length - num_paddings ) _UpperCAmelCase : Dict = tokenizer.batch_decode(A , skip_special_tokens=A ) _UpperCAmelCase : Any = tokenizer.decode(output_non_padded[0] , skip_special_tokens=A ) _UpperCAmelCase : Optional[int] = tokenizer.decode(output_padded[0] , skip_special_tokens=A ) _UpperCAmelCase : str = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(A , A ) self.assertListEqual(A , [non_padded_sentence, padded_sentence] ) @slow def _A ( self : str ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase : Optional[Any] = BioGptModel.from_pretrained(A ) self.assertIsNotNone(A ) def _A ( self : List[str] ): _UpperCAmelCase , _UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase : str = 3 _UpperCAmelCase : List[str] = input_dict["input_ids"] _UpperCAmelCase : Dict = input_ids.ne(1 ).to(A ) _UpperCAmelCase : List[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _UpperCAmelCase : List[str] = BioGptForSequenceClassification(A ) model.to(A ) model.eval() _UpperCAmelCase : List[str] = model(A , attention_mask=A , labels=A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _A ( self : int ): _UpperCAmelCase , _UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase : int = 3 _UpperCAmelCase : Dict = "multi_label_classification" _UpperCAmelCase : Optional[Any] = input_dict["input_ids"] _UpperCAmelCase : Optional[int] = input_ids.ne(1 ).to(A ) _UpperCAmelCase : Tuple = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _UpperCAmelCase : Optional[Any] = BioGptForSequenceClassification(A ) model.to(A ) model.eval() _UpperCAmelCase : Tuple = model(A , attention_mask=A , labels=A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class lowerCamelCase_ (unittest.TestCase ): '''simple docstring''' @slow def _A ( self : List[Any] ): _UpperCAmelCase : Optional[Any] = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) _UpperCAmelCase : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) _UpperCAmelCase : List[Any] = model(A )[0] _UpperCAmelCase : int = 42384 _UpperCAmelCase : int = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , A ) _UpperCAmelCase : Any = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , A , atol=1E-4 ) ) @slow def _A ( self : Any ): _UpperCAmelCase : str = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) _UpperCAmelCase : Tuple = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(A ) torch.manual_seed(0 ) _UpperCAmelCase : Optional[Any] = tokenizer("COVID-19 is" , return_tensors="pt" ).to(A ) _UpperCAmelCase : Dict = model.generate( **A , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=A , ) _UpperCAmelCase : Optional[Any] = tokenizer.decode(output_ids[0] , skip_special_tokens=A ) _UpperCAmelCase : List[str] = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(A , A )
31
1
SCREAMING_SNAKE_CASE__ = 8.3144598 def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: float , __lowerCamelCase: float ): '''simple docstring''' if temperature < 0: raise Exception("Temperature cannot be less than 0 K" ) if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol" ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example SCREAMING_SNAKE_CASE__ = 3_0_0 SCREAMING_SNAKE_CASE__ = 2_8 SCREAMING_SNAKE_CASE__ = rms_speed_of_molecule(temperature, molar_mass) print(f"""Vrms of Nitrogen gas at 300 K is {vrms} m/s""")
360
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class __lowerCamelCase ( snake_case_ , snake_case_ ): """simple docstring""" lowerCAmelCase__ = 1 @register_to_config def __init__( self , UpperCAmelCase = 1000 , UpperCAmelCase = None ) -> List[Any]: '''simple docstring''' self.set_timesteps(UpperCAmelCase ) # standard deviation of the initial noise distribution lowercase_ = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. lowercase_ = 4 # running values lowercase_ = [] def A__ ( self , UpperCAmelCase , UpperCAmelCase = None ) -> Optional[int]: '''simple docstring''' lowercase_ = num_inference_steps lowercase_ = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] lowercase_ = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: lowercase_ = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: lowercase_ = torch.sin(steps * math.pi / 2 ) ** 2 lowercase_ = (1.0 - self.betas**2) ** 0.5 lowercase_ = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] lowercase_ = timesteps.to(UpperCAmelCase ) lowercase_ = [] def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = True , ) -> Union[SchedulerOutput, Tuple]: '''simple docstring''' if self.num_inference_steps is None: raise ValueError( "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" ) lowercase_ = (self.timesteps == timestep).nonzero().item() lowercase_ = timestep_index + 1 lowercase_ = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCAmelCase ) if len(self.ets ) == 1: lowercase_ = self.ets[-1] elif len(self.ets ) == 2: lowercase_ = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: lowercase_ = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: lowercase_ = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) lowercase_ = self._get_prev_sample(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCAmelCase ) def A__ ( self , UpperCAmelCase , *UpperCAmelCase , **UpperCAmelCase ) -> torch.FloatTensor: '''simple docstring''' return sample def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Dict: '''simple docstring''' lowercase_ = self.alphas[timestep_index] lowercase_ = self.betas[timestep_index] lowercase_ = self.alphas[prev_timestep_index] lowercase_ = self.betas[prev_timestep_index] lowercase_ = (sample - sigma * ets) / max(UpperCAmelCase , 1e-8 ) lowercase_ = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self ) -> List[str]: '''simple docstring''' return self.config.num_train_timesteps
297
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 __UpperCamelCase : Any = '''sshleifer/bart-tiny-random''' __UpperCamelCase : List[Any] = '''patrickvonplaten/t5-tiny-random''' @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @cached_property def __lowerCAmelCase ( self : Optional[Any] ): return AutoConfig.from_pretrained(lowercase_ ) def __lowerCAmelCase ( self : Union[str, Any] ): lowerCAmelCase__ ,*lowerCAmelCase__ : Tuple = create_student_by_copying_alternating_layers(lowercase_ ,tempfile.mkdtemp() ,e=1 ,d=1 ) self.assertEqual(student.config.num_hidden_layers ,1 ) def __lowerCAmelCase ( self : int ): lowerCAmelCase__ ,*lowerCAmelCase__ : Any = create_student_by_copying_alternating_layers(lowercase_ ,tempfile.mkdtemp() ,e=1 ,d=lowercase_ ) def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ ,*lowerCAmelCase__ : List[Any] = create_student_by_copying_alternating_layers(lowercase_ ,tempfile.mkdtemp() ,e=1 ,d=lowercase_ ) self.assertEqual(student.config.encoder_layers ,1 ) self.assertEqual(student.config.decoder_layers ,self.teacher_config.encoder_layers ) def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ ,*lowerCAmelCase__ : List[str] = create_student_by_copying_alternating_layers(lowercase_ ,tempfile.mkdtemp() ,e=1 ,d=1 ) self.assertEqual(student.config.encoder_layers ,1 ) self.assertEqual(student.config.decoder_layers ,1 ) def __lowerCAmelCase ( self : Optional[Any] ): with self.assertRaises(lowercase_ ): create_student_by_copying_alternating_layers(lowercase_ ,tempfile.mkdtemp() ,e=lowercase_ ,d=lowercase_ )
106
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __UpperCamelCase : Dict = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = ['''CLIPFeatureExtractor'''] __UpperCamelCase : Optional[Any] = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys __UpperCamelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
106
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class lowerCAmelCase ( unittest.TestCase ): def __init__( self : Any , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : List[str]=7 , UpperCAmelCase : List[Any]=3 , UpperCAmelCase : int=30 , UpperCAmelCase : Any=400 , UpperCAmelCase : List[str]=True , UpperCAmelCase : Any=None , UpperCAmelCase : Union[str, Any]=True , UpperCAmelCase : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase : List[Any]=[0.5, 0.5, 0.5] , UpperCAmelCase : str=True , UpperCAmelCase : Optional[int]=1 / 255 , UpperCAmelCase : Dict=True , ) -> Tuple: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowerCamelCase__ : Dict = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} lowerCamelCase__ : str = parent lowerCamelCase__ : Optional[int] = batch_size lowerCamelCase__ : int = num_channels lowerCamelCase__ : int = min_resolution lowerCamelCase__ : Dict = max_resolution lowerCamelCase__ : Dict = do_resize lowerCamelCase__ : Any = size lowerCamelCase__ : Any = do_normalize lowerCamelCase__ : int = image_mean lowerCamelCase__ : Tuple = image_std lowerCamelCase__ : Optional[int] = do_rescale lowerCamelCase__ : str = rescale_factor lowerCamelCase__ : Optional[int] = do_pad def A_ ( self : List[str] ) -> Union[str, Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def A_ ( self : Optional[Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : Union[str, Any]=False ) -> Tuple: if not batched: lowerCamelCase__ : Dict = image_inputs[0] if isinstance(UpperCAmelCase , Image.Image ): lowerCamelCase__ , lowerCamelCase__ : Tuple = image.size else: lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = image.shape[1], image.shape[2] if w < h: lowerCamelCase__ : str = int(self.size['shortest_edge'] * h / w ) lowerCamelCase__ : str = self.size['shortest_edge'] elif w > h: lowerCamelCase__ : int = self.size['shortest_edge'] lowerCamelCase__ : Optional[int] = int(self.size['shortest_edge'] * w / h ) else: lowerCamelCase__ : List[Any] = self.size['shortest_edge'] lowerCamelCase__ : int = self.size['shortest_edge'] else: lowerCamelCase__ : List[Any] = [] for image in image_inputs: lowerCamelCase__ , lowerCamelCase__ : Dict = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCamelCase__ : List[str] = max(UpperCAmelCase , key=lambda UpperCAmelCase : item[0] )[0] lowerCamelCase__ : List[Any] = max(UpperCAmelCase , key=lambda UpperCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase ( __UpperCamelCase, unittest.TestCase ): UpperCAmelCase__ = ConditionalDetrImageProcessor if is_vision_available() else None def A_ ( self : Any ) -> Dict: lowerCamelCase__ : Any = ConditionalDetrImageProcessingTester(self ) @property def A_ ( self : Union[str, Any] ) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def A_ ( self : str ) -> Dict: lowerCamelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase , 'image_mean' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'image_std' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'do_normalize' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'size' ) ) def A_ ( self : List[Any] ) -> int: lowerCamelCase__ : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , UpperCAmelCase ) lowerCamelCase__ : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=UpperCAmelCase ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Optional[int]: pass def A_ ( self : Tuple ) -> List[Any]: # Initialize image_processing lowerCamelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , Image.Image ) # Test not batched input lowerCamelCase__ : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.image_processor_tester.get_expected_values(UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase__ , lowerCamelCase__ : Optional[int] = self.image_processor_tester.get_expected_values(UpperCAmelCase , batched=UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A_ ( self : int ) -> int: # Initialize image_processing lowerCamelCase__ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase__ : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , numpify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , np.ndarray ) # Test not batched input lowerCamelCase__ : Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCamelCase__ , lowerCamelCase__ : Tuple = self.image_processor_tester.get_expected_values(UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase__ : List[Any] = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values lowerCamelCase__ , lowerCamelCase__ : Dict = self.image_processor_tester.get_expected_values(UpperCAmelCase , batched=UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A_ ( self : Optional[Any] ) -> Tuple: # Initialize image_processing lowerCamelCase__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , torchify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCamelCase__ : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCamelCase__ , lowerCamelCase__ : int = self.image_processor_tester.get_expected_values(UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase__ : List[str] = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values lowerCamelCase__ , lowerCamelCase__ : Any = self.image_processor_tester.get_expected_values(UpperCAmelCase , batched=UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def A_ ( self : Tuple ) -> int: # prepare image and target lowerCamelCase__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: lowerCamelCase__ : int = json.loads(f.read() ) lowerCamelCase__ : Any = {'image_id': 39769, 'annotations': target} # encode them lowerCamelCase__ : Any = ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) lowerCamelCase__ : Union[str, Any] = image_processing(images=UpperCAmelCase , annotations=UpperCAmelCase , return_tensors='pt' ) # verify pixel values lowerCamelCase__ : List[str] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , UpperCAmelCase , atol=1e-4 ) ) # verify area lowerCamelCase__ : Optional[int] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , UpperCAmelCase ) ) # verify boxes lowerCamelCase__ : str = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , UpperCAmelCase ) lowerCamelCase__ : Optional[int] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , UpperCAmelCase , atol=1e-3 ) ) # verify image_id lowerCamelCase__ : Any = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , UpperCAmelCase ) ) # verify is_crowd lowerCamelCase__ : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , UpperCAmelCase ) ) # verify class_labels lowerCamelCase__ : Dict = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , UpperCAmelCase ) ) # verify orig_size lowerCamelCase__ : Union[str, Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , UpperCAmelCase ) ) # verify size lowerCamelCase__ : Union[str, Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , UpperCAmelCase ) ) @slow def A_ ( self : int ) -> Union[str, Any]: # prepare image, target and masks_path lowerCamelCase__ : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: lowerCamelCase__ : Dict = json.loads(f.read() ) lowerCamelCase__ : Optional[int] = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} lowerCamelCase__ : Tuple = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them lowerCamelCase__ : Union[str, Any] = ConditionalDetrImageProcessor(format='coco_panoptic' ) lowerCamelCase__ : Optional[Any] = image_processing(images=UpperCAmelCase , annotations=UpperCAmelCase , masks_path=UpperCAmelCase , return_tensors='pt' ) # verify pixel values lowerCamelCase__ : Dict = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , UpperCAmelCase , atol=1e-4 ) ) # verify area lowerCamelCase__ : str = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , UpperCAmelCase ) ) # verify boxes lowerCamelCase__ : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , UpperCAmelCase , atol=1e-3 ) ) # verify image_id lowerCamelCase__ : Tuple = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , UpperCAmelCase ) ) # verify is_crowd lowerCamelCase__ : int = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , UpperCAmelCase ) ) # verify class_labels lowerCamelCase__ : Dict = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , UpperCAmelCase ) ) # verify masks lowerCamelCase__ : List[Any] = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , UpperCAmelCase ) # verify orig_size lowerCamelCase__ : Tuple = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , UpperCAmelCase ) ) # verify size lowerCamelCase__ : Union[str, Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , UpperCAmelCase ) )
45
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCAmelCase : List[Any] = logging.get_logger(__name__) _UpperCAmelCase : Union[str, Any] = { """google/efficientnet-b7""": """https://huggingface.co/google/efficientnet-b7/resolve/main/config.json""", } class lowerCAmelCase ( __UpperCamelCase ): UpperCAmelCase__ = """efficientnet""" def __init__( self : Tuple , UpperCAmelCase : int = 3 , UpperCAmelCase : int = 600 , UpperCAmelCase : float = 2.0 , UpperCAmelCase : float = 3.1 , UpperCAmelCase : int = 8 , UpperCAmelCase : List[int] = [3, 3, 5, 3, 5, 5, 3] , UpperCAmelCase : List[int] = [32, 16, 24, 40, 80, 112, 192] , UpperCAmelCase : List[int] = [16, 24, 40, 80, 112, 192, 320] , UpperCAmelCase : List[int] = [] , UpperCAmelCase : List[int] = [1, 2, 2, 2, 1, 2, 1] , UpperCAmelCase : List[int] = [1, 2, 2, 3, 3, 4, 1] , UpperCAmelCase : List[int] = [1, 6, 6, 6, 6, 6, 6] , UpperCAmelCase : float = 0.2_5 , UpperCAmelCase : str = "swish" , UpperCAmelCase : int = 2560 , UpperCAmelCase : str = "mean" , UpperCAmelCase : float = 0.0_2 , UpperCAmelCase : float = 0.0_0_1 , UpperCAmelCase : float = 0.9_9 , UpperCAmelCase : float = 0.5 , UpperCAmelCase : float = 0.2 , **UpperCAmelCase : int , ) -> Any: super().__init__(**UpperCAmelCase ) lowerCamelCase__ : List[Any] = num_channels lowerCamelCase__ : List[str] = image_size lowerCamelCase__ : Union[str, Any] = width_coefficient lowerCamelCase__ : Optional[Any] = depth_coefficient lowerCamelCase__ : Union[str, Any] = depth_divisor lowerCamelCase__ : Dict = kernel_sizes lowerCamelCase__ : Union[str, Any] = in_channels lowerCamelCase__ : Dict = out_channels lowerCamelCase__ : Dict = depthwise_padding lowerCamelCase__ : int = strides lowerCamelCase__ : List[str] = num_block_repeats lowerCamelCase__ : Optional[Any] = expand_ratios lowerCamelCase__ : List[str] = squeeze_expansion_ratio lowerCamelCase__ : int = hidden_act lowerCamelCase__ : int = hidden_dim lowerCamelCase__ : int = pooling_type lowerCamelCase__ : Optional[Any] = initializer_range lowerCamelCase__ : Any = batch_norm_eps lowerCamelCase__ : List[Any] = batch_norm_momentum lowerCamelCase__ : int = dropout_rate lowerCamelCase__ : int = drop_connect_rate lowerCamelCase__ : List[Any] = sum(UpperCAmelCase ) * 4 class lowerCAmelCase ( __UpperCamelCase ): UpperCAmelCase__ = version.parse("""1.11""" ) @property def A_ ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def A_ ( self : List[Any] ) -> float: return 1e-5
45
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class lowercase ( unittest.TestCase ): def a__ ( self ) -> Optional[Any]: _A : str = tempfile.mkdtemp() _A : List[Any] = BlipImageProcessor() _A : Optional[Any] = GPTaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-GPT2Model""" ) _A : Tuple = BertTokenizerFast.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) _A : Any = InstructBlipProcessor(_a , _a , _a ) processor.save_pretrained(self.tmpdirname ) def a__ ( self , **_a ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).tokenizer def a__ ( self , **_a ) -> int: return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def a__ ( self , **_a ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).qformer_tokenizer def a__ ( self ) -> int: shutil.rmtree(self.tmpdirname ) def a__ ( self ) -> Optional[Any]: _A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _A : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def a__ ( self ) -> Union[str, Any]: _A : Tuple = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) _A : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _A : Tuple = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) _A : Tuple = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) self.assertIsInstance(processor.qformer_tokenizer , _a ) def a__ ( self ) -> Dict: _A : int = self.get_image_processor() _A : Dict = self.get_tokenizer() _A : Dict = self.get_qformer_tokenizer() _A : int = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Optional[Any] = self.prepare_image_inputs() _A : List[Any] = image_processor(_a , return_tensors="""np""" ) _A : str = processor(images=_a , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a__ ( self ) -> Union[str, Any]: _A : Optional[int] = self.get_image_processor() _A : Optional[int] = self.get_tokenizer() _A : List[Any] = self.get_qformer_tokenizer() _A : List[Any] = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Optional[int] = """lower newer""" _A : List[str] = processor(text=_a ) _A : str = tokenizer(_a , return_token_type_ids=_a ) _A : List[str] = qformer_tokenizer(_a , return_token_type_ids=_a ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor["""qformer_""" + key] ) def a__ ( self ) -> List[str]: _A : Any = self.get_image_processor() _A : List[str] = self.get_tokenizer() _A : Dict = self.get_qformer_tokenizer() _A : List[str] = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Tuple = """lower newer""" _A : Optional[int] = self.prepare_image_inputs() _A : Any = processor(text=_a , images=_a ) self.assertListEqual( list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""] , ) # test if it raises when no input is passed with pytest.raises(_a ): processor() def a__ ( self ) -> Dict: _A : Dict = self.get_image_processor() _A : Any = self.get_tokenizer() _A : str = self.get_qformer_tokenizer() _A : int = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _A : List[str] = processor.batch_decode(_a ) _A : Optional[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def a__ ( self ) -> str: _A : List[Any] = self.get_image_processor() _A : Optional[int] = self.get_tokenizer() _A : int = self.get_qformer_tokenizer() _A : List[Any] = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Dict = """lower newer""" _A : int = self.prepare_image_inputs() _A : int = processor(text=_a , images=_a ) self.assertListEqual( list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""] , )
26
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class lowercase ( UpperCamelCase__ ): _a = "xmod" def __init__( self , _a=3_0522 , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1e-12 , _a=1 , _a=0 , _a=2 , _a="absolute" , _a=True , _a=None , _a=False , _a=2 , _a=False , _a=True , _a=True , _a=("en_XX",) , _a=None , **_a , ) -> str: super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) _A : Tuple = vocab_size _A : Union[str, Any] = hidden_size _A : Dict = num_hidden_layers _A : Dict = num_attention_heads _A : List[Any] = hidden_act _A : Optional[Any] = intermediate_size _A : Any = hidden_dropout_prob _A : str = attention_probs_dropout_prob _A : Dict = max_position_embeddings _A : Any = type_vocab_size _A : List[Any] = initializer_range _A : int = layer_norm_eps _A : int = position_embedding_type _A : Any = use_cache _A : int = classifier_dropout _A : int = pre_norm _A : Optional[Any] = adapter_reduction_factor _A : List[Any] = adapter_layer_norm _A : Optional[int] = adapter_reuse_layer_norm _A : Any = ln_before_adapter _A : Union[str, Any] = list(_a ) _A : List[Any] = default_language class lowercase ( UpperCamelCase__ ): @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _A : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _A : Dict = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
26
1
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : Tuple = [False] * len(_UpperCamelCase ) snake_case_ : Dict = [] queue.append(_UpperCamelCase ) snake_case_ : Union[str, Any] = True while queue: snake_case_ : Optional[int] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(_UpperCamelCase ) snake_case_ : Any = True snake_case_ : Optional[int] = u return visited[t] def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Tuple = [-1] * (len(_UpperCamelCase )) snake_case_ : Optional[int] = 0 while bfs(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): snake_case_ : Tuple = float('''Inf''' ) snake_case_ : List[Any] = sink while s != source: # Find the minimum value in select path snake_case_ : Any = min(_UpperCamelCase , graph[parent[s]][s] ) snake_case_ : Union[str, Any] = parent[s] max_flow += path_flow snake_case_ : str = sink while v != source: snake_case_ : int = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow snake_case_ : int = parent[v] return max_flow lowerCAmelCase_ = [ [0, 1_6, 1_3, 0, 0, 0], [0, 0, 1_0, 1_2, 0, 0], [0, 4, 0, 0, 1_4, 0], [0, 0, 9, 0, 0, 2_0], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] lowerCAmelCase_ , lowerCAmelCase_ = 0, 5 print(ford_fulkerson(graph, source, sink))
368
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __lowerCAmelCase ( unittest.TestCase ): @property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.dummy_uncond_unet snake_case_ : Optional[Any] = PNDMScheduler() snake_case_ : Optional[Any] = PNDMPipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pndm.to(__magic_name__ ) pndm.set_progress_bar_config(disable=__magic_name__ ) snake_case_ : str = torch.manual_seed(0 ) snake_case_ : Dict = pndm(generator=__magic_name__ , num_inference_steps=20 , output_type='''numpy''' ).images snake_case_ : str = torch.manual_seed(0 ) snake_case_ : str = pndm(generator=__magic_name__ , num_inference_steps=20 , output_type='''numpy''' , return_dict=__magic_name__ )[0] snake_case_ : Any = image[0, -3:, -3:, -1] snake_case_ : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case_ : str = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Tuple = '''google/ddpm-cifar10-32''' snake_case_ : Tuple = UNetaDModel.from_pretrained(__magic_name__ ) snake_case_ : Optional[Any] = PNDMScheduler() snake_case_ : Any = PNDMPipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pndm.to(__magic_name__ ) pndm.set_progress_bar_config(disable=__magic_name__ ) snake_case_ : int = torch.manual_seed(0 ) snake_case_ : Tuple = pndm(generator=__magic_name__ , output_type='''numpy''' ).images snake_case_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case_ : str = np.array([0.1_564, 0.14_645, 0.1_406, 0.14_715, 0.12_425, 0.14_045, 0.13_115, 0.12_175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
279
0
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller a_ :List[str] = 3 def lowercase_ (A : int ): print('Generating primitive root of p' ) while True: snake_case__ : Optional[int] = random.randrange(3 , A ) if pow(A , 2 , A ) == 1: continue if pow(A , A , A ) == 1: continue return g def lowercase_ (A : int ): print('Generating prime p...' ) snake_case__ : Dict = rabin_miller.generate_large_prime(A ) # select large prime number. snake_case__ : Union[str, Any] = primitive_root(A ) # one primitive root on modulo p. snake_case__ : Dict = random.randrange(3 , A ) # private_key -> have to be greater than 2 for safety. snake_case__ : Any = cryptomath.find_mod_inverse(pow(A , A , A ) , A ) snake_case__ : str = (key_size, e_a, e_a, p) snake_case__ : Union[str, Any] = (key_size, d) return public_key, private_key def lowercase_ (A : str , A : 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() snake_case__ , snake_case__ : List[Any] = generate_key(A ) 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' , 2_0_4_8 ) print('Key files generation successful' ) if __name__ == "__main__": main()
277
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() a_ :Dict = logging.get_logger(__name__) def lowercase_ (A : Optional[Any] , A : Any=False ): snake_case__ : List[Any] = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('head' ): snake_case__ : str = 'segformer.encoder.' + key if key.startswith('backbone' ): snake_case__ : str = key.replace('backbone' , 'segformer.encoder' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 snake_case__ : Optional[int] = key[key.find('patch_embed' ) + len('patch_embed' )] snake_case__ : int = key.replace(F'''patch_embed{idx}''' , F'''patch_embeddings.{int(A )-1}''' ) if "norm" in key: snake_case__ : Optional[int] = key.replace('norm' , 'layer_norm' ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 snake_case__ : Tuple = key[key.find('segformer.encoder.layer_norm' ) + len('segformer.encoder.layer_norm' )] snake_case__ : Union[str, Any] = key.replace(F'''layer_norm{idx}''' , F'''layer_norm.{int(A )-1}''' ) if "layer_norm1" in key: snake_case__ : List[Any] = key.replace('layer_norm1' , 'layer_norm_1' ) if "layer_norm2" in key: snake_case__ : List[Any] = key.replace('layer_norm2' , 'layer_norm_2' ) if "block" in key: # replace for example block1 by block.0 snake_case__ : List[Any] = key[key.find('block' ) + len('block' )] snake_case__ : List[Any] = key.replace(F'''block{idx}''' , F'''block.{int(A )-1}''' ) if "attn.q" in key: snake_case__ : int = key.replace('attn.q' , 'attention.self.query' ) if "attn.proj" in key: snake_case__ : str = key.replace('attn.proj' , 'attention.output.dense' ) if "attn" in key: snake_case__ : Optional[int] = key.replace('attn' , 'attention.self' ) if "fc1" in key: snake_case__ : str = key.replace('fc1' , 'dense1' ) if "fc2" in key: snake_case__ : Dict = key.replace('fc2' , 'dense2' ) if "linear_pred" in key: snake_case__ : Union[str, Any] = key.replace('linear_pred' , 'classifier' ) if "linear_fuse" in key: snake_case__ : List[str] = key.replace('linear_fuse.conv' , 'linear_fuse' ) snake_case__ : List[Any] = key.replace('linear_fuse.bn' , 'batch_norm' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 snake_case__ : Optional[int] = key[key.find('linear_c' ) + len('linear_c' )] snake_case__ : Tuple = key.replace(F'''linear_c{idx}''' , F'''linear_c.{int(A )-1}''' ) if key.startswith('head' ): snake_case__ : Tuple = key.replace('head' , 'classifier' ) snake_case__ : Optional[int] = value return new_state_dict def lowercase_ (A : Tuple , A : Optional[int] ): # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) snake_case__ : List[str] = state_dict.pop(F'''segformer.encoder.block.{i}.{j}.attention.self.kv.weight''' ) snake_case__ : Optional[Any] = state_dict.pop(F'''segformer.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict snake_case__ : str = kv_weight[ : config.hidden_sizes[i], : ] snake_case__ : Dict = kv_bias[: config.hidden_sizes[i]] snake_case__ : List[str] = kv_weight[ config.hidden_sizes[i] :, : ] snake_case__ : List[Any] = kv_bias[ config.hidden_sizes[i] : ] def lowercase_ (): snake_case__ : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case__ : Dict = Image.open(requests.get(A , stream=A ).raw ) return image @torch.no_grad() def lowercase_ (A : Any , A : Union[str, Any] , A : Optional[Any] ): snake_case__ : List[str] = SegformerConfig() snake_case__ : Dict = False # set attributes based on model_name snake_case__ : Optional[int] = 'huggingface/label-files' if "segformer" in model_name: snake_case__ : str = model_name[len('segformer.' ) : len('segformer.' ) + 2] if "ade" in model_name: snake_case__ : Optional[int] = 1_5_0 snake_case__ : int = 'ade20k-id2label.json' snake_case__ : List[Any] = (1, 1_5_0, 1_2_8, 1_2_8) elif "city" in model_name: snake_case__ : str = 1_9 snake_case__ : List[str] = 'cityscapes-id2label.json' snake_case__ : Optional[Any] = (1, 1_9, 1_2_8, 1_2_8) else: raise ValueError(F'''Model {model_name} not supported''' ) elif "mit" in model_name: snake_case__ : str = True snake_case__ : Union[str, Any] = model_name[4:6] snake_case__ : Optional[Any] = 1_0_0_0 snake_case__ : Optional[int] = 'imagenet-1k-id2label.json' snake_case__ : List[Any] = (1, 1_0_0_0) else: raise ValueError(F'''Model {model_name} not supported''' ) # set config attributes snake_case__ : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) snake_case__ : List[Any] = {int(A ): v for k, v in idalabel.items()} snake_case__ : Union[str, Any] = idalabel snake_case__ : Tuple = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": snake_case__ : List[Any] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : Tuple = 2_5_6 elif size == "b2": snake_case__ : List[str] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : int = 7_6_8 snake_case__ : List[Any] = [3, 4, 6, 3] elif size == "b3": snake_case__ : Optional[Any] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : int = 7_6_8 snake_case__ : Optional[Any] = [3, 4, 1_8, 3] elif size == "b4": snake_case__ : str = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : Optional[Any] = 7_6_8 snake_case__ : Union[str, Any] = [3, 8, 2_7, 3] elif size == "b5": snake_case__ : List[str] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : Optional[Any] = 7_6_8 snake_case__ : Any = [3, 6, 4_0, 3] else: raise ValueError(F'''Size {size} not supported''' ) # load image processor (only resize + normalize) snake_case__ : Dict = SegformerImageProcessor( image_scale=(5_1_2, 5_1_2) , keep_ratio=A , align=A , do_random_crop=A ) # prepare image snake_case__ : List[str] = prepare_img() snake_case__ : Dict = image_processor(images=A , return_tensors='pt' ).pixel_values logger.info(F'''Converting model {model_name}...''' ) # load original state dict if encoder_only: snake_case__ : Tuple = torch.load(A , map_location=torch.device('cpu' ) ) else: snake_case__ : int = torch.load(A , map_location=torch.device('cpu' ) )['state_dict'] # rename keys snake_case__ : List[Any] = rename_keys(A , encoder_only=A ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(A , A ) # create HuggingFace model and load state dict if encoder_only: snake_case__ : str = False snake_case__ : List[Any] = SegformerForImageClassification(A ) else: snake_case__ : Dict = SegformerForSemanticSegmentation(A ) model.load_state_dict(A ) model.eval() # forward pass snake_case__ : int = model(A ) snake_case__ : Any = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": snake_case__ : Dict = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": snake_case__ : Optional[int] = torch.tensor( [ [[-7.5820, -8.7231, -8.3215], [-8.0600, -10.3529, -10.0304], [-7.5208, -9.4103, -9.6239]], [[-12.6918, -13.8994, -13.7137], [-13.3196, -15.7523, -15.4789], [-12.9343, -14.8757, -14.9689]], [[-11.1911, -11.9421, -11.3243], [-11.3342, -13.6839, -13.3581], [-10.3909, -12.1832, -12.4858]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": snake_case__ : List[Any] = torch.tensor( [ [[-11.8173, -14.3850, -16.3128], [-14.5648, -16.5804, -18.6568], [-14.7223, -15.7387, -18.4218]], [[-15.7290, -17.9171, -19.4423], [-18.3105, -19.9448, -21.4661], [-17.9296, -18.6497, -20.7910]], [[-15.0783, -17.0336, -18.2789], [-16.8771, -18.6870, -20.1612], [-16.2454, -17.1426, -19.5055]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": snake_case__ : Union[str, Any] = torch.tensor( [ [[-9.0878, -10.2081, -10.1891], [-9.3144, -10.7941, -10.9843], [-9.2294, -10.3855, -10.5704]], [[-12.2316, -13.9068, -13.6102], [-12.9161, -14.3702, -14.3235], [-12.5233, -13.7174, -13.7932]], [[-14.6275, -15.2490, -14.9727], [-14.3400, -15.9687, -16.2827], [-14.1484, -15.4033, -15.8937]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": snake_case__ : Dict = torch.tensor( [ [[-12.3144, -13.2447, -14.0802], [-13.3614, -14.5816, -15.6117], [-13.3340, -14.4433, -16.2219]], [[-19.2781, -20.4128, -20.7506], [-20.6153, -21.6566, -22.0998], [-19.9800, -21.0430, -22.1494]], [[-18.8739, -19.7804, -21.1834], [-20.1233, -21.6765, -23.2944], [-20.0315, -21.2641, -23.6944]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": snake_case__ : List[Any] = torch.tensor( [ [[-9.5524, -12.0835, -11.7348], [-10.5229, -13.6446, -14.5662], [-9.5842, -12.8851, -13.9414]], [[-15.3432, -17.5323, -17.0818], [-16.3330, -18.9255, -19.2101], [-15.1340, -17.7848, -18.3971]], [[-12.6072, -14.9486, -14.6631], [-13.7629, -17.0907, -17.7745], [-12.7899, -16.1695, -17.1671]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": snake_case__ : str = torch.tensor( [ [[-11.9295, -13.4057, -14.8106], [-13.3431, -14.8179, -15.3781], [-14.2836, -15.5942, -16.1588]], [[-11.4906, -12.8067, -13.6564], [-13.1189, -14.0500, -14.1543], [-13.8748, -14.5136, -14.8789]], [[0.5374, 0.1067, -0.4742], [0.1141, -0.2255, -0.7099], [-0.3000, -0.5924, -1.3105]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": snake_case__ : Tuple = torch.tensor( [ [[-7.8217, -9.8767, -10.1717], [-9.4438, -10.9058, -11.4047], [-9.7939, -12.3495, -12.1079]], [[-7.1514, -9.5336, -10.0860], [-9.7776, -11.6822, -11.8439], [-10.1411, -12.7655, -12.8972]], [[0.3021, 0.0805, -0.2310], [-0.0328, -0.1605, -0.2714], [-0.1408, -0.5477, -0.6976]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": snake_case__ : Any = torch.tensor( [ [ [-1.1_372e01, -1.2_787e01, -1.3_477e01], [-1.2_536e01, -1.4_194e01, -1.4_409e01], [-1.3_217e01, -1.4_888e01, -1.5_327e01], ], [ [-1.4_791e01, -1.7_122e01, -1.8_277e01], [-1.7_163e01, -1.9_192e01, -1.9_533e01], [-1.7_897e01, -1.9_991e01, -2.0_315e01], ], [ [7.6_723e-01, 4.1_921e-01, -7.7_878e-02], [4.7_772e-01, 9.5_557e-03, -2.8_082e-01], [3.6_032e-01, -2.4_826e-01, -5.1_168e-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": snake_case__ : Optional[int] = torch.tensor( [ [[-9.4959, -11.3087, -11.7479], [-11.0025, -12.6540, -12.3319], [-11.4064, -13.0487, -12.9905]], [[-9.8905, -11.3084, -12.0854], [-11.1726, -12.7698, -12.9583], [-11.5985, -13.3278, -14.1774]], [[0.2213, 0.0192, -0.2466], [-0.1731, -0.4213, -0.4874], [-0.3126, -0.6541, -1.1389]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": snake_case__ : Union[str, Any] = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": snake_case__ : List[str] = torch.tensor( [ [[-16.0976, -16.4856, -17.3962], [-16.6234, -19.0342, -19.7685], [-16.0900, -18.0661, -19.1180]], [[-18.4750, -18.8488, -19.5074], [-19.4030, -22.1570, -22.5977], [-19.1191, -20.8486, -22.3783]], [[-4.5178, -5.5037, -6.5109], [-5.0884, -7.2174, -8.0334], [-4.4156, -5.8117, -7.2970]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": snake_case__ : List[Any] = torch.tensor( [ [[-14.2081, -14.4732, -14.1977], [-14.5867, -16.4423, -16.6356], [-13.4441, -14.9685, -16.8696]], [[-14.4576, -14.7073, -15.0451], [-15.0816, -17.6237, -17.9873], [-14.4213, -16.0199, -18.5992]], [[-4.7349, -4.9588, -5.0966], [-4.3210, -6.9325, -7.2591], [-3.4312, -4.7484, -7.1917]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": snake_case__ : str = torch.tensor( [ [[-11.7737, -11.9526, -11.3273], [-13.6692, -14.4574, -13.8878], [-13.8937, -14.6924, -15.9345]], [[-14.6706, -14.5330, -14.1306], [-16.1502, -16.8180, -16.4269], [-16.8338, -17.8939, -20.1746]], [[1.0491, 0.8289, 1.0310], [1.1044, 0.5219, 0.8055], [1.0899, 0.6926, 0.5590]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": snake_case__ : List[str] = torch.tensor( [ [[-12.5641, -13.4777, -13.0684], [-13.9587, -15.8983, -16.6557], [-13.3109, -15.7350, -16.3141]], [[-14.7074, -15.4352, -14.5944], [-16.6353, -18.1663, -18.6120], [-15.1702, -18.0329, -18.1547]], [[-1.7990, -2.0951, -1.7784], [-2.6397, -3.8245, -3.9686], [-1.5264, -2.8126, -2.9316]], ] ) else: snake_case__ : Tuple = logits.argmax(-1 ).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , A , atol=1e-2 ) # finally, 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 __name__ == "__main__": a_ :Optional[int] = argparse.ArgumentParser() parser.add_argument( "--model_name", default="segformer.b0.512x512.ade.160k", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) a_ :Union[str, Any] = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
277
1
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging UpperCAmelCase__ : str =logging.get_logger(__name__) class __A ( a ): __A = ["""input_features""", """is_longer"""] def __init__( self , UpperCAmelCase_=64 , UpperCAmelCase_=48000 , UpperCAmelCase_=480 , UpperCAmelCase_=10 , UpperCAmelCase_=1024 , UpperCAmelCase_=0.0 , UpperCAmelCase_=False , UpperCAmelCase_ = 0 , UpperCAmelCase_ = 14000 , UpperCAmelCase_ = None , UpperCAmelCase_ = "fusion" , UpperCAmelCase_ = "repeatpad" , **UpperCAmelCase_ , ): super().__init__( feature_size=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , padding_value=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , **UpperCAmelCase_ , ) lowerCamelCase =top_db lowerCamelCase =truncation lowerCamelCase =padding lowerCamelCase =fft_window_size lowerCamelCase =(fft_window_size >> 1) + 1 lowerCamelCase =hop_length lowerCamelCase =max_length_s lowerCamelCase =max_length_s * sampling_rate lowerCamelCase =sampling_rate lowerCamelCase =frequency_min lowerCamelCase =frequency_max lowerCamelCase =mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCAmelCase_ , min_frequency=UpperCAmelCase_ , max_frequency=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , norm=UpperCAmelCase_ , mel_scale="""htk""" , ) lowerCamelCase =mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCAmelCase_ , min_frequency=UpperCAmelCase_ , max_frequency=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , norm="""slaney""" , mel_scale="""slaney""" , ) def _snake_case ( self ): lowerCamelCase =copy.deepcopy(self.__dict__ ) lowerCamelCase =self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =spectrogram( UpperCAmelCase_ , window_function(self.fft_window_size , """hann""" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCAmelCase_ , log_mel="""dB""" , ) return log_mel_spectrogram.T def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): lowerCamelCase =np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk lowerCamelCase =[0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk lowerCamelCase =[0] # randomly choose index for each part lowerCamelCase =np.random.choice(ranges[0] ) lowerCamelCase =np.random.choice(ranges[1] ) lowerCamelCase =np.random.choice(ranges[2] ) lowerCamelCase =mel[idx_front : idx_front + chunk_frames, :] lowerCamelCase =mel[idx_middle : idx_middle + chunk_frames, :] lowerCamelCase =mel[idx_back : idx_back + chunk_frames, :] lowerCamelCase =torch.tensor(mel[None, None, :] ) lowerCamelCase =torch.nn.functional.interpolate( UpperCAmelCase_ , size=[chunk_frames, 64] , mode="""bilinear""" , align_corners=UpperCAmelCase_ ) lowerCamelCase =mel_shrink[0][0].numpy() lowerCamelCase =np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): if waveform.shape[0] > max_length: if truncation == "rand_trunc": lowerCamelCase =True # random crop to max_length (for compatibility) -> this should be handled by self.pad lowerCamelCase =len(UpperCAmelCase_ ) - max_length lowerCamelCase =np.random.randint(0 , overflow + 1 ) lowerCamelCase =waveform[idx : idx + max_length] lowerCamelCase =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": lowerCamelCase =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters ) lowerCamelCase =max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed lowerCamelCase =mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. lowerCamelCase =np.stack([mel, mel, mel, mel] , axis=0 ) lowerCamelCase =False else: lowerCamelCase =self._random_mel_fusion(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) lowerCamelCase =True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: lowerCamelCase =False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": lowerCamelCase =int(max_length / len(UpperCAmelCase_ ) ) lowerCamelCase =np.stack(np.tile(UpperCAmelCase_ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": lowerCamelCase =int(max_length / len(UpperCAmelCase_ ) ) lowerCamelCase =np.stack(np.tile(UpperCAmelCase_ , UpperCAmelCase_ ) ) lowerCamelCase =np.pad(UpperCAmelCase_ , (0, max_length - waveform.shape[0]) , mode="""constant""" , constant_values=0 ) if truncation == "fusion": lowerCamelCase =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters ) lowerCamelCase =np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: lowerCamelCase =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self , UpperCAmelCase_ , UpperCAmelCase_ = None , UpperCAmelCase_ = None , UpperCAmelCase_ = None , UpperCAmelCase_ = None , UpperCAmelCase_ = None , **UpperCAmelCase_ , ): lowerCamelCase =truncation if truncation is not None else self.truncation lowerCamelCase =padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) lowerCamelCase =isinstance(UpperCAmelCase_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) lowerCamelCase =is_batched_numpy or ( isinstance(UpperCAmelCase_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCamelCase =[np.asarray(UpperCAmelCase_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(UpperCAmelCase_ , np.ndarray ): lowerCamelCase =np.asarray(UpperCAmelCase_ , dtype=np.floataa ) elif isinstance(UpperCAmelCase_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowerCamelCase =raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowerCamelCase =[np.asarray(UpperCAmelCase_ )] # convert to mel spectrogram, truncate and pad if needed. lowerCamelCase =[ self._get_input_mel(UpperCAmelCase_ , max_length if max_length else self.nb_max_samples , UpperCAmelCase_ , UpperCAmelCase_ ) for waveform in raw_speech ] lowerCamelCase =[] lowerCamelCase =[] for mel, longer in padded_inputs: input_mel.append(UpperCAmelCase_ ) is_longer.append(UpperCAmelCase_ ) if truncation == "fusion" and sum(UpperCAmelCase_ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer lowerCamelCase =np.random.randint(0 , len(UpperCAmelCase_ ) ) lowerCamelCase =True if isinstance(input_mel[0] , UpperCAmelCase_ ): lowerCamelCase =[np.asarray(UpperCAmelCase_ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool lowerCamelCase =[[longer] for longer in is_longer] lowerCamelCase ={"""input_features""": input_mel, """is_longer""": is_longer} lowerCamelCase =BatchFeature(UpperCAmelCase_ ) if return_tensors is not None: lowerCamelCase =input_features.convert_to_tensors(UpperCAmelCase_ ) return input_features
262
import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor UpperCAmelCase__ : Optional[int] =logging.getLogger(__name__) UpperCAmelCase__ : Tuple =50 # max width of layer names UpperCAmelCase__ : List[str] =70 # max width of quantizer names def _lowercase ( _UpperCAmelCase ) -> List[str]: lowerCamelCase =parser.add_argument_group("""quant_trainer arguments""" ) group.add_argument("""--wprec""" , type=_UpperCAmelCase , default=8 , help="""weight precision""" ) group.add_argument("""--aprec""" , type=_UpperCAmelCase , default=8 , help="""activation precision""" ) group.add_argument("""--quant-per-tensor""" , action="""store_true""" , help="""per tensor weight scaling""" ) group.add_argument("""--quant-disable""" , action="""store_true""" , help="""disable all quantizers""" ) group.add_argument("""--quant-disable-embeddings""" , action="""store_true""" , help="""disable all embeddings quantizers""" ) group.add_argument("""--quant-disable-keyword""" , type=_UpperCAmelCase , nargs="""+""" , help="""disable quantizers by keyword""" ) group.add_argument("""--quant-disable-layer-module""" , type=_UpperCAmelCase , help="""disable quantizers by keyword under layer.""" ) group.add_argument("""--quant-enable-layer-module""" , type=_UpperCAmelCase , help="""enable quantizers by keyword under layer""" ) group.add_argument("""--calibrator""" , default="""max""" , help="""which quantization range calibrator to use""" ) group.add_argument("""--percentile""" , default=_UpperCAmelCase , type=_UpperCAmelCase , help="""percentile for PercentileCalibrator""" ) group.add_argument("""--fuse-qkv""" , action="""store_true""" , help="""use the same scale factor for qkv""" ) group.add_argument("""--clip-gelu""" , metavar="""N""" , type=_UpperCAmelCase , help="""clip gelu output maximum value to N""" ) group.add_argument( """--recalibrate-weights""" , action="""store_true""" , help=( """recalibrate weight amaxes by taking the max of the weights.""" """ amaxes will be computed with the current quantization granularity (axis).""" ) , ) def _lowercase ( _UpperCAmelCase ) -> Dict: if args.calibrator == "max": lowerCamelCase ="""max""" elif args.calibrator == "percentile": if args.percentile is None: raise ValueError("""Specify --percentile when using percentile calibrator""" ) lowerCamelCase ="""histogram""" elif args.calibrator == "mse": lowerCamelCase ="""histogram""" else: raise ValueError(F"""Invalid calibrator {args.calibrator}""" ) lowerCamelCase =QuantDescriptor(num_bits=args.aprec , calib_method=_UpperCAmelCase ) lowerCamelCase =QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,)) ) quant_nn.QuantLinear.set_default_quant_desc_input(_UpperCAmelCase ) quant_nn.QuantLinear.set_default_quant_desc_weight(_UpperCAmelCase ) def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=False ) -> int: logger.info("""Configuring Model for Quantization""" ) logger.info(F"""using quantization package {pytorch_quantization.__file__}""" ) if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(_UpperCAmelCase , ["""embeddings"""] , which="""weight""" , _disabled=_UpperCAmelCase ) if args.quant_disable: set_quantizer_by_name(_UpperCAmelCase , [""""""] , _disabled=_UpperCAmelCase ) if args.quant_disable_keyword: set_quantizer_by_name(_UpperCAmelCase , args.quant_disable_keyword , _disabled=_UpperCAmelCase ) if args.quant_disable_layer_module: set_quantizer_by_name(_UpperCAmelCase , [r"""layer.\d+.""" + args.quant_disable_layer_module] , _disabled=_UpperCAmelCase ) if args.quant_enable_layer_module: set_quantizer_by_name(_UpperCAmelCase , [r"""layer.\d+.""" + args.quant_enable_layer_module] , _disabled=_UpperCAmelCase ) if args.recalibrate_weights: recalibrate_weights(_UpperCAmelCase ) if args.fuse_qkv: fuse_qkv(_UpperCAmelCase , _UpperCAmelCase ) if args.clip_gelu: clip_gelu(_UpperCAmelCase , args.clip_gelu ) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(_UpperCAmelCase ) def _lowercase ( _UpperCAmelCase ) -> Optional[Any]: logger.info("""Enabling Calibration""" ) for name, module in model.named_modules(): if name.endswith("""_quantizer""" ): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(F"""{name:80}: {module}""" ) def _lowercase ( _UpperCAmelCase , _UpperCAmelCase ) -> Optional[int]: logger.info("""Loading calibrated amax""" ) for name, module in model.named_modules(): if name.endswith("""_quantizer""" ): if module._calibrator is not None: if isinstance(module._calibrator , calib.MaxCalibrator ): module.load_calib_amax() else: module.load_calib_amax("""percentile""" , percentile=args.percentile ) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(_UpperCAmelCase ) def _lowercase ( _UpperCAmelCase , _UpperCAmelCase ) -> Tuple: def fusea(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): for mod in [qq, qk, qv]: if not hasattr(_UpperCAmelCase , """_amax""" ): print(""" WARNING: NO AMAX BUFFER""" ) return lowerCamelCase =qq._amax.detach().item() lowerCamelCase =qk._amax.detach().item() lowerCamelCase =qv._amax.detach().item() lowerCamelCase =max(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) qq._amax.fill_(_UpperCAmelCase ) qk._amax.fill_(_UpperCAmelCase ) qv._amax.fill_(_UpperCAmelCase ) logger.info(F""" q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}""" ) for name, mod in model.named_modules(): if name.endswith(""".attention.self""" ): logger.info(F"""FUSE_QKV: {name:{name_width}}""" ) fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer ) if args.quant_per_tensor: fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer ) def _lowercase ( _UpperCAmelCase , _UpperCAmelCase ) -> int: for name, mod in model.named_modules(): if name.endswith(""".output.dense""" ) and not name.endswith("""attention.output.dense""" ): lowerCamelCase =mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=_UpperCAmelCase ) lowerCamelCase =mod._input_quantizer._amax.data.detach().item() logger.info(F"""CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}""" ) def _lowercase ( _UpperCAmelCase ) -> Dict: for name, mod in model.named_modules(): if hasattr(_UpperCAmelCase , """_weight_quantizer""" ) and mod._weight_quantizer.axis is not None: lowerCamelCase =mod.weight.shape[0] lowerCamelCase =mod._weight_quantizer._amax.detach() lowerCamelCase =torch.ones(_UpperCAmelCase , dtype=amax.dtype , device=amax.device ) * amax print(F"""expanding {name} {amax} -> {mod._weight_quantizer._amax}""" ) def _lowercase ( _UpperCAmelCase ) -> List[str]: for name, mod in model.named_modules(): if hasattr(_UpperCAmelCase , """_weight_quantizer""" ): if not hasattr(mod.weight_quantizer , """_amax""" ): print("""RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER""" ) continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) lowerCamelCase =set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis ) lowerCamelCase =set(range(len(mod.weight.size() ) ) ) - axis_set lowerCamelCase =pytorch_quantization.utils.reduce_amax(mod.weight , axis=_UpperCAmelCase , keepdims=_UpperCAmelCase ).detach() logger.info(F"""RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}""" ) lowerCamelCase =amax def _lowercase ( _UpperCAmelCase , _UpperCAmelCase=25 , _UpperCAmelCase=1_80 , _UpperCAmelCase=None ) -> Dict: if ignore is None: lowerCamelCase =[] elif not isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowerCamelCase =[ignore] lowerCamelCase =0 for name, mod in model.named_modules(): if not hasattr(_UpperCAmelCase , """weight""" ): continue lowerCamelCase =max(_UpperCAmelCase , len(_UpperCAmelCase ) ) for name, mod in model.named_modules(): lowerCamelCase =getattr(_UpperCAmelCase , """_input_quantizer""" , _UpperCAmelCase ) lowerCamelCase =getattr(_UpperCAmelCase , """_weight_quantizer""" , _UpperCAmelCase ) if not hasattr(_UpperCAmelCase , """weight""" ): continue if type(_UpperCAmelCase ) in ignore: continue if [True for s in ignore if type(_UpperCAmelCase ) is str and s in name]: continue lowerCamelCase =F"""Act:{input_q.extra_repr()}""" lowerCamelCase =F"""Wgt:{weight_q.extra_repr()}""" lowerCamelCase =F"""{name:{name_width}} {act_str} {wgt_str}""" if len(_UpperCAmelCase ) <= line_width: logger.info(_UpperCAmelCase ) else: logger.info(F"""{name:{name_width}} {act_str}""" ) logger.info(F"""{" ":{name_width}} {wgt_str}""" ) def _lowercase ( _UpperCAmelCase ) -> Dict: lowerCamelCase =0 for name, mod in model.named_modules(): if isinstance(_UpperCAmelCase , pytorch_quantization.nn.TensorQuantizer ): print(F"""{name:80} {mod}""" ) count += 1 print(F"""{count} TensorQuantizers found in model""" ) def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: lowerCamelCase =getattr(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if quantizer_mod is not None: assert hasattr(_UpperCAmelCase , _UpperCAmelCase ) setattr(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) else: logger.warning(F"""{name} has no {quantizer}""" ) def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase="both" , **_UpperCAmelCase ) -> List[str]: lowerCamelCase =F"""Warning: changing {which} quantizers of {name:{qname_width}}""" for k, v in kwargs.items(): s += F""" {k}={v}""" if which in ["input", "both"]: set_quantizer(_UpperCAmelCase , _UpperCAmelCase , """_input_quantizer""" , _UpperCAmelCase , _UpperCAmelCase ) if which in ["weight", "both"]: set_quantizer(_UpperCAmelCase , _UpperCAmelCase , """_weight_quantizer""" , _UpperCAmelCase , _UpperCAmelCase ) logger.info(_UpperCAmelCase ) def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase ) -> int: for name, mod in model.named_modules(): if hasattr(_UpperCAmelCase , """_input_quantizer""" ) or hasattr(_UpperCAmelCase , """_weight_quantizer""" ): for n in names: if re.search(_UpperCAmelCase , _UpperCAmelCase ): set_quantizers(_UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase ) elif name.endswith("""_quantizer""" ): for n in names: if re.search(_UpperCAmelCase , _UpperCAmelCase ): lowerCamelCase =F"""Warning: changing {name:{name_width}}""" for k, v in kwargs.items(): s += F""" {k}={v}""" setattr(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) logger.info(_UpperCAmelCase )
262
1
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class A__ ( A__ ): def A ( self : Optional[Any] ) -> str: '''simple docstring''' return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE ={'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} return Dataset.from_dict(_a ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._create_example_records() _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) self.assertListEqual(dset.column_names , ['col_1', 'col_2'] ) for i, r in enumerate(_a ): self.assertDictEqual(_a , example_records[i] ) def A ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._create_example_records() _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) _SCREAMING_SNAKE_CASE =Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def A ( self : Any ) -> List[Any]: # checks what happens with missing columns '''simple docstring''' _SCREAMING_SNAKE_CASE =[{'col_1': 1}, {'col_2': 'x'}] _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) self.assertDictEqual(dset[0] , {'col_1': 1} ) self.assertDictEqual(dset[1] , {'col_1': None} ) # NB: first record is used for columns def A ( self : str ) -> int: # checks if the type can be inferred from the second record '''simple docstring''' _SCREAMING_SNAKE_CASE =[{'col_1': []}, {'col_1': [1, 2]}] _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) self.assertEqual(dset.info.features['col_1'] , Sequence(Value('int64' ) ) ) def A ( self : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =Dataset.from_list([] ) self.assertEqual(len(_a ) , 0 ) self.assertListEqual(dset.column_names , [] )
47
_lowerCamelCase : Optional[int] = 65521 def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" A__ = 1 A__ = 0 for plain_chr in plain_text: A__ = (a + ord(lowercase_ )) % MOD_ADLER A__ = (b + a) % MOD_ADLER return (b << 16) | a
14
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class _a ( _lowercase): _a : Union[str, Any] = '''altclip_text_model''' def __init__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any]=25_0002 , _SCREAMING_SNAKE_CASE : Union[str, Any]=1024 , _SCREAMING_SNAKE_CASE : List[str]=24 , _SCREAMING_SNAKE_CASE : List[Any]=16 , _SCREAMING_SNAKE_CASE : Dict=4096 , _SCREAMING_SNAKE_CASE : List[Any]="gelu" , _SCREAMING_SNAKE_CASE : List[Any]=0.1 , _SCREAMING_SNAKE_CASE : int=0.1 , _SCREAMING_SNAKE_CASE : Optional[Any]=514 , _SCREAMING_SNAKE_CASE : List[Any]=1 , _SCREAMING_SNAKE_CASE : Dict=0.02 , _SCREAMING_SNAKE_CASE : str=0.02 , _SCREAMING_SNAKE_CASE : Any=1E-05 , _SCREAMING_SNAKE_CASE : List[str]=1 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0 , _SCREAMING_SNAKE_CASE : Dict=2 , _SCREAMING_SNAKE_CASE : Dict="absolute" , _SCREAMING_SNAKE_CASE : List[Any]=True , _SCREAMING_SNAKE_CASE : int=768 , **_SCREAMING_SNAKE_CASE : Any , )-> Any: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : Optional[int] = vocab_size lowerCAmelCase__ : Optional[Any] = hidden_size lowerCAmelCase__ : Union[str, Any] = num_hidden_layers lowerCAmelCase__ : Dict = num_attention_heads lowerCAmelCase__ : Optional[int] = hidden_act lowerCAmelCase__ : List[str] = intermediate_size lowerCAmelCase__ : Dict = hidden_dropout_prob lowerCAmelCase__ : Dict = attention_probs_dropout_prob lowerCAmelCase__ : Optional[Any] = max_position_embeddings lowerCAmelCase__ : Dict = type_vocab_size lowerCAmelCase__ : Optional[Any] = initializer_range lowerCAmelCase__ : Any = initializer_factor lowerCAmelCase__ : List[str] = layer_norm_eps lowerCAmelCase__ : List[Any] = position_embedding_type lowerCAmelCase__ : Tuple = use_cache lowerCAmelCase__ : List[str] = project_dim class _a ( _lowercase): _a : Optional[Any] = '''altclip_vision_model''' def __init__( self : List[Any] , _SCREAMING_SNAKE_CASE : List[str]=768 , _SCREAMING_SNAKE_CASE : Any=3072 , _SCREAMING_SNAKE_CASE : Dict=512 , _SCREAMING_SNAKE_CASE : Dict=12 , _SCREAMING_SNAKE_CASE : Optional[int]=12 , _SCREAMING_SNAKE_CASE : List[str]=3 , _SCREAMING_SNAKE_CASE : Union[str, Any]=224 , _SCREAMING_SNAKE_CASE : Optional[int]=32 , _SCREAMING_SNAKE_CASE : Dict="quick_gelu" , _SCREAMING_SNAKE_CASE : Union[str, Any]=1E-5 , _SCREAMING_SNAKE_CASE : int=0.0 , _SCREAMING_SNAKE_CASE : Dict=0.02 , _SCREAMING_SNAKE_CASE : List[str]=1.0 , **_SCREAMING_SNAKE_CASE : str , )-> int: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : Tuple = hidden_size lowerCAmelCase__ : List[str] = intermediate_size lowerCAmelCase__ : Optional[Any] = projection_dim lowerCAmelCase__ : Tuple = num_hidden_layers lowerCAmelCase__ : Dict = num_attention_heads lowerCAmelCase__ : Any = num_channels lowerCAmelCase__ : int = patch_size lowerCAmelCase__ : str = image_size lowerCAmelCase__ : Dict = initializer_range lowerCAmelCase__ : Optional[Any] = initializer_factor lowerCAmelCase__ : Dict = attention_dropout lowerCAmelCase__ : Optional[Any] = layer_norm_eps lowerCAmelCase__ : Optional[int] = hidden_act @classmethod def UpperCAmelCase__( cls : Tuple , _SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **_SCREAMING_SNAKE_CASE : List[str] )-> "PretrainedConfig": cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : List[Any] = cls.get_config_dict(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get('''model_type''' ) == "altclip": lowerCAmelCase__ : List[Any] = 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(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) class _a ( _lowercase): _a : str = '''altclip''' _a : int = True def __init__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : Any=None , _SCREAMING_SNAKE_CASE : Optional[int]=None , _SCREAMING_SNAKE_CASE : Any=768 , _SCREAMING_SNAKE_CASE : Optional[int]=2.6592 , **_SCREAMING_SNAKE_CASE : int )-> List[Any]: # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). lowerCAmelCase__ : List[Any] = kwargs.pop('''text_config_dict''' , _SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : int = kwargs.pop('''vision_config_dict''' , _SCREAMING_SNAKE_CASE ) super().__init__(**_SCREAMING_SNAKE_CASE ) # 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: lowerCAmelCase__ : Optional[int] = {} # This is the complete result when using `text_config_dict`. lowerCAmelCase__ : Optional[int] = AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE ).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: lowerCAmelCase__ : List[Any] = ( 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: lowerCAmelCase__ : List[Any] = ( F'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ' F'value `text_config["{key}"]` will be overriden.' ) logger.warning(_SCREAMING_SNAKE_CASE ) # 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: lowerCAmelCase__ : List[Any] = {} # This is the complete result when using `vision_config_dict`. lowerCAmelCase__ : List[Any] = AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: lowerCAmelCase__ : Union[str, Any] = { str(_SCREAMING_SNAKE_CASE ): 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: lowerCAmelCase__ : Tuple = ( 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: lowerCAmelCase__ : List[str] = ( F'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ' F'The value `vision_config["{key}"]` will be overriden.' ) logger.warning(_SCREAMING_SNAKE_CASE ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: lowerCAmelCase__ : Tuple = {} logger.info('''`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.''' ) if vision_config is None: lowerCAmelCase__ : Optional[int] = {} logger.info('''`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.''' ) lowerCAmelCase__ : List[Any] = AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : Dict = AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : Tuple = projection_dim lowerCAmelCase__ : Tuple = logit_scale_init_value lowerCAmelCase__ : Any = 1.0 @classmethod def UpperCAmelCase__( cls : int , _SCREAMING_SNAKE_CASE : AltCLIPTextConfig , _SCREAMING_SNAKE_CASE : AltCLIPVisionConfig , **_SCREAMING_SNAKE_CASE : str )-> Dict: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__( self : int )-> Optional[int]: lowerCAmelCase__ : Dict = copy.deepcopy(self.__dict__ ) lowerCAmelCase__ : str = self.text_config.to_dict() lowerCAmelCase__ : List[Any] = self.vision_config.to_dict() lowerCAmelCase__ : List[Any] = self.__class__.model_type return output
366
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json''' ), } class _a ( _lowercase): _a : List[Any] = '''dpr''' def __init__( self : List[str] , _SCREAMING_SNAKE_CASE : List[str]=3_0522 , _SCREAMING_SNAKE_CASE : Optional[int]=768 , _SCREAMING_SNAKE_CASE : List[str]=12 , _SCREAMING_SNAKE_CASE : Tuple=12 , _SCREAMING_SNAKE_CASE : str=3072 , _SCREAMING_SNAKE_CASE : Optional[Any]="gelu" , _SCREAMING_SNAKE_CASE : Dict=0.1 , _SCREAMING_SNAKE_CASE : Optional[int]=0.1 , _SCREAMING_SNAKE_CASE : List[str]=512 , _SCREAMING_SNAKE_CASE : int=2 , _SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , _SCREAMING_SNAKE_CASE : Tuple=1E-12 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0 , _SCREAMING_SNAKE_CASE : List[str]="absolute" , _SCREAMING_SNAKE_CASE : int = 0 , **_SCREAMING_SNAKE_CASE : Optional[Any] , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : Union[str, Any] = vocab_size lowerCAmelCase__ : Tuple = hidden_size lowerCAmelCase__ : Union[str, Any] = num_hidden_layers lowerCAmelCase__ : List[Any] = num_attention_heads lowerCAmelCase__ : Optional[int] = hidden_act lowerCAmelCase__ : Optional[Any] = intermediate_size lowerCAmelCase__ : Optional[Any] = hidden_dropout_prob lowerCAmelCase__ : int = attention_probs_dropout_prob lowerCAmelCase__ : str = max_position_embeddings lowerCAmelCase__ : List[Any] = type_vocab_size lowerCAmelCase__ : Optional[int] = initializer_range lowerCAmelCase__ : List[str] = layer_norm_eps lowerCAmelCase__ : Dict = projection_dim lowerCAmelCase__ : int = position_embedding_type
211
0
"""simple docstring""" import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def lowercase_ ( _snake_case ,_snake_case ): assert isinstance(_snake_case ,_snake_case ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def lowercase_ ( _snake_case ,_snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE__ : Optional[int] = SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_snake_case ,keep_in_memory=_snake_case ).read() _check_sql_dataset(_snake_case ,_snake_case ) @require_sqlalchemy @pytest.mark.parametrize( """features""" ,[ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] ,) def lowercase_ ( _snake_case ,_snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Any = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Tuple = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} SCREAMING_SNAKE_CASE__ : Dict = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE__ : Any = ( Features({feature: Value(_snake_case ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE__ : int = SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_snake_case ,cache_dir=_snake_case ).read() _check_sql_dataset(_snake_case ,_snake_case ) def lowercase_ ( _snake_case ): with contextlib.closing(sqlitea.connect(_snake_case ) ) as con: SCREAMING_SNAKE_CASE__ : Optional[int] = con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Any = os.path.join(_snake_case ,"""tmp.sql""" ) SCREAMING_SNAKE_CASE__ : Dict = SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_snake_case ).read() SqlDatasetWriter(_snake_case ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() SCREAMING_SNAKE_CASE__ : List[str] = iter_sql_file(_snake_case ) SCREAMING_SNAKE_CASE__ : int = iter_sql_file(_snake_case ) for rowa, rowa in zip(_snake_case ,_snake_case ): assert rowa == rowa @require_sqlalchemy def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(_snake_case ,"""tmp.sql""" ) SCREAMING_SNAKE_CASE__ : int = SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_snake_case ).read() SqlDatasetWriter(_snake_case ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() SCREAMING_SNAKE_CASE__ : Any = iter_sql_file(_snake_case ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = iter_sql_file(_snake_case ) for rowa, rowa in zip(_snake_case ,_snake_case ): assert rowa == rowa @require_sqlalchemy def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_snake_case ,"""tmp.sql""" ) SCREAMING_SNAKE_CASE__ : Any = SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_snake_case ).read() with pytest.raises(_snake_case ): SqlDatasetWriter(_snake_case ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
25
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowerCAmelCase_ : """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(poly_a or [0] )[:] SCREAMING_SNAKE_CASE__ : Tuple = list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() SCREAMING_SNAKE_CASE__ : int = len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() SCREAMING_SNAKE_CASE__ : List[str] = len(self.polyB ) # Add 0 to make lengths equal a power of 2 SCREAMING_SNAKE_CASE__ : Optional[int] = 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 SCREAMING_SNAKE_CASE__ : List[str] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product SCREAMING_SNAKE_CASE__ : Tuple = self.__multiply() def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE__ ) <= 1: return dft[0] # SCREAMING_SNAKE_CASE__ : Optional[Any] = self.c_max_length // 2 while next_ncol > 0: SCREAMING_SNAKE_CASE__ : Any = [[] for i in range(SCREAMING_SNAKE_CASE__ )] SCREAMING_SNAKE_CASE__ : Tuple = self.root**next_ncol # First half of next step SCREAMING_SNAKE_CASE__ : str = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(SCREAMING_SNAKE_CASE__ ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step SCREAMING_SNAKE_CASE__ : int = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(SCREAMING_SNAKE_CASE__ ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update SCREAMING_SNAKE_CASE__ : Union[str, Any] = new_dft SCREAMING_SNAKE_CASE__ : Tuple = next_ncol // 2 return dft[0] def __magic_name__ (self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.__dft("""A""" ) SCREAMING_SNAKE_CASE__ : Dict = self.__dft("""B""" ) SCREAMING_SNAKE_CASE__ : List[Any] = [[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 SCREAMING_SNAKE_CASE__ : Optional[Any] = 2 while next_ncol <= self.c_max_length: SCREAMING_SNAKE_CASE__ : List[str] = [[] for i in range(SCREAMING_SNAKE_CASE__ )] SCREAMING_SNAKE_CASE__ : Tuple = self.root ** (next_ncol // 2) SCREAMING_SNAKE_CASE__ : Any = 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 SCREAMING_SNAKE_CASE__ : Optional[Any] = new_inverse_c next_ncol *= 2 # Unpack SCREAMING_SNAKE_CASE__ : Optional[Any] = [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 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """A = """ + """ + """.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """B = """ + """ + """.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) ) SCREAMING_SNAKE_CASE__ : int = """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()
25
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = SwinvaConfig() __SCREAMING_SNAKE_CASE = swinva_name.split("""_""" ) __SCREAMING_SNAKE_CASE = name_split[1] if "to" in name_split[3]: __SCREAMING_SNAKE_CASE = int(name_split[3][-3:] ) else: __SCREAMING_SNAKE_CASE = int(name_split[3] ) if "to" in name_split[2]: __SCREAMING_SNAKE_CASE = int(name_split[2][-2:] ) else: __SCREAMING_SNAKE_CASE = int(name_split[2][6:] ) if model_size == "tiny": __SCREAMING_SNAKE_CASE = 96 __SCREAMING_SNAKE_CASE = (2, 2, 6, 2) __SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": __SCREAMING_SNAKE_CASE = 96 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": __SCREAMING_SNAKE_CASE = 128 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: __SCREAMING_SNAKE_CASE = 192 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "to" in swinva_name: __SCREAMING_SNAKE_CASE = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): __SCREAMING_SNAKE_CASE = 2_1841 __SCREAMING_SNAKE_CASE = '''huggingface/label-files''' __SCREAMING_SNAKE_CASE = '''imagenet-22k-id2label.json''' __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__a , __a , repo_type="""dataset""" ) , """r""" ) ) __SCREAMING_SNAKE_CASE = {int(__a ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} else: __SCREAMING_SNAKE_CASE = 1000 __SCREAMING_SNAKE_CASE = '''huggingface/label-files''' __SCREAMING_SNAKE_CASE = '''imagenet-1k-id2label.json''' __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__a , __a , repo_type="""dataset""" ) , """r""" ) ) __SCREAMING_SNAKE_CASE = {int(__a ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = img_size __SCREAMING_SNAKE_CASE = num_classes __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size return config def _lowerCAmelCase ( UpperCamelCase_ ): if "patch_embed.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: __SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: __SCREAMING_SNAKE_CASE = '''encoder.''' + name if "attn.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if "q_bias" in name: __SCREAMING_SNAKE_CASE = name.replace("""q_bias""" , """query.bias""" ) if "k_bias" in name: __SCREAMING_SNAKE_CASE = name.replace("""k_bias""" , """key.bias""" ) if "v_bias" in name: __SCREAMING_SNAKE_CASE = name.replace("""v_bias""" , """value.bias""" ) if "cpb_mlp" in name: __SCREAMING_SNAKE_CASE = name.replace("""cpb_mlp""" , """continuous_position_bias_mlp""" ) if name == "norm.weight": __SCREAMING_SNAKE_CASE = '''layernorm.weight''' if name == "norm.bias": __SCREAMING_SNAKE_CASE = '''layernorm.bias''' if "head" in name: __SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: __SCREAMING_SNAKE_CASE = '''swinv2.''' + name return name def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE = orig_state_dict.pop(__a ) if "mask" in key: continue elif "qkv" in key: __SCREAMING_SNAKE_CASE = key.split(""".""" ) __SCREAMING_SNAKE_CASE = int(key_split[1] ) __SCREAMING_SNAKE_CASE = int(key_split[3] ) __SCREAMING_SNAKE_CASE = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __SCREAMING_SNAKE_CASE = val[:dim, :] __SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] __SCREAMING_SNAKE_CASE = val[-dim:, :] else: __SCREAMING_SNAKE_CASE = val[:dim] __SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE = val[-dim:] else: __SCREAMING_SNAKE_CASE = val return orig_state_dict def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = timm.create_model(__a , pretrained=__a ) timm_model.eval() __SCREAMING_SNAKE_CASE = get_swinva_config(__a ) __SCREAMING_SNAKE_CASE = SwinvaForImageClassification(__a ) model.eval() __SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , __a ) model.load_state_dict(__a ) __SCREAMING_SNAKE_CASE = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swinva_name.replace("""_""" , """-""" ) ) ) __SCREAMING_SNAKE_CASE = Image.open(requests.get(__a , stream=__a ).raw ) __SCREAMING_SNAKE_CASE = image_processor(images=__a , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) __SCREAMING_SNAKE_CASE = model(**__a ).logits assert torch.allclose(__a , __a , atol=1e-3 ) print(f"Saving model {swinva_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__a ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__a ) model.push_to_hub( repo_path_or_name=Path(__a , __a ) , organization="""nandwalritik""" , commit_message="""Add model""" , ) if __name__ == "__main__": __magic_name__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swinv2_name", default="swinv2_tiny_patch4_window8_256", type=str, help="Name of the Swinv2 timm model you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) __magic_name__ = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
365
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version __magic_name__ = { "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt, } def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): if got_ver is None or want_ver is None: raise ValueError( f"Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider" f" reinstalling {pkg}." ) if not ops[op](version.parse(UpperCamelCase_ ) , version.parse(UpperCamelCase_ ) ): raise ImportError( f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}" ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ = None ): __SCREAMING_SNAKE_CASE = f"\n{hint}" if hint is not None else """""" # non-versioned check if re.match(r"""^[\w_\-\d]+$""" , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = requirement, None, None else: __SCREAMING_SNAKE_CASE = re.findall(r"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , UpperCamelCase_ ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" f" got {requirement}" ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = match[0] __SCREAMING_SNAKE_CASE = want_full.split(""",""" ) # there could be multiple requirements __SCREAMING_SNAKE_CASE = {} for w in want_range: __SCREAMING_SNAKE_CASE = re.findall(r"""^([\s!=<>]{1,2})(.+)""" , UpperCamelCase_ ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" f" but got {requirement}" ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = match[0] __SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(f"{requirement}: need one of {list(ops.keys() )}, but got {op}" ) # special case if pkg == "python": __SCREAMING_SNAKE_CASE = """.""".join([str(UpperCamelCase_ ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) return # check if any version is installed try: __SCREAMING_SNAKE_CASE = importlib.metadata.version(UpperCamelCase_ ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( f"The '{requirement}' distribution was not found and is required by this application. {hint}" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(UpperCamelCase_ , UpperCamelCase_ )
255
0
"""simple docstring""" from functools import reduce __snake_case : Any = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _lowercase ( __snake_case = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda __snake_case ,__snake_case : str(int(__snake_case ) * int(__snake_case ) ) ,n[i : i + 13] ) ) for i in range(len(__snake_case ) - 12 ) ) if __name__ == "__main__": print(F"""{solution() = }""")
269
"""simple docstring""" import os from math import logaa def _lowercase ( __snake_case = "base_exp.txt" ) -> int: __lowerCAmelCase : float = 0 __lowerCAmelCase : Any = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(__snake_case ) ,__snake_case ) ) ): __lowerCAmelCase , __lowerCAmelCase : List[str] = list(map(__snake_case ,line.split("," ) ) ) if x * logaa(__snake_case ) > largest: __lowerCAmelCase : Tuple = x * logaa(__snake_case ) __lowerCAmelCase : Optional[Any] = i + 1 return result if __name__ == "__main__": print(solution())
269
1
'''simple docstring''' def lowerCamelCase__ ( _A ): a : Dict = 1 a : Optional[int] = 2 while i * i <= n: a : Tuple = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def lowerCamelCase__ ( ): a : int = 1 a : int = 1 while True: i += 1 t_num += i if count_divisors(_A ) > 500: break return t_num if __name__ == "__main__": print(solution())
350
'''simple docstring''' # Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def lowerCamelCase__ ( _A , _A , _A=0 ): # Format the message. if name is None: a : Tuple = None else: a : Dict = '.' * max(0 , spaces - 2 ) + '# {:' + str(50 - spaces ) + 's}' a : Tuple = fmt.format(_A ) # Print and recurse (if needed). if isinstance(_A , _A ): if msg is not None: print(_A ) for k in val.keys(): recursive_print(_A , val[k] , spaces + 2 ) elif isinstance(_A , torch.Tensor ): print(_A , ':' , val.size() ) else: print(_A , ':' , _A ) def lowerCamelCase__ ( _A , _A , _A , _A , _A ): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. a : str = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] a : List[Any] = (num_heads, hidden_size, num_splits) + input_shape[1:] a : int = param.view(*_A ) a : List[str] = param.transpose(0 , 2 ) a : Union[str, Any] = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] a : Union[str, Any] = (num_heads, num_splits, hidden_size) + input_shape[1:] a : List[str] = param.view(*_A ) a : Union[str, Any] = param.transpose(0 , 1 ).contiguous() a : List[Any] = param.view(*_A ) return param def lowerCamelCase__ ( _A , _A , _A ): # The converted output model. a : Optional[Any] = {} # old versions did not store training args a : Dict = input_state_dict.get('args' , _A ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) a : Union[str, Any] = ds_args.padded_vocab_size a : str = ds_args.max_position_embeddings a : Dict = ds_args.hidden_size a : Union[str, Any] = ds_args.num_layers a : Dict = ds_args.num_attention_heads a : int = ds_args.ffn_hidden_size # pprint(config) # The number of heads. a : Any = config.n_head # The hidden_size per head. a : Tuple = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): a : Any = input_state_dict['checkpoint_version'] else: a : Any = 0.0 # The model. a : Optional[int] = input_state_dict['model'] # The language model. a : Optional[Any] = model['language_model'] # The embeddings. a : List[str] = lm['embedding'] # The word embeddings. a : List[Any] = embeddings['word_embeddings']['weight'] # Truncate the embedding table to vocab_size rows. a : Dict = word_embeddings[: config.vocab_size, :] a : int = word_embeddings # The position embeddings. a : Tuple = embeddings['position_embeddings']['weight'] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] a : List[str] = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f"""pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match""" ) # Store the position embeddings. a : Optional[Any] = pos_embeddings # The transformer. a : Union[str, Any] = lm['transformer'] if 'transformer' in lm.keys() else lm['encoder'] # The regex to extract layer names. a : List[Any] = re.compile(r'layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)' ) # The simple map of names for "automated" rules. a : Optional[Any] = { 'attention.dense': '.attn.c_proj.', 'self_attention.dense': '.attn.c_proj.', 'mlp.dense_h_to_4h': '.mlp.c_fc.', 'mlp.dense_4h_to_h': '.mlp.c_proj.', } # Extract the layers. for key, val in transformer.items(): # Match the name. a : Tuple = layer_re.match(_A ) # Stop if that's not a layer if m is None: break # The index of the layer. a : Union[str, Any] = int(m.group(1 ) ) # The name of the operation. a : Optional[int] = m.group(2 ) # Is it a weight or a bias? a : Optional[int] = m.group(3 ) # The name of the layer. a : Any = f"""transformer.h.{layer_idx}""" # For layernorm(s), simply store the layer norm. if op_name.endswith('layernorm' ): a : str = 'ln_1' if op_name.startswith('input' ) else 'ln_2' a : Tuple = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. a : Dict = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , _A , _A ) a : Optional[Any] = causal_mask # Insert a "dummy" tensor for masked_bias. a : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) a : List[str] = masked_bias a : Union[str, Any] = fix_query_key_value_ordering(_A , _A , 3 , _A , _A ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. a : int = out_val.transpose(0 , 1 ).contiguous() # Store. a : int = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": a : str = fix_query_key_value_ordering(_A , _A , 3 , _A , _A ) # Store. No change of shape. a : List[str] = out_val # Transpose the weights. elif weight_or_bias == "weight": a : Tuple = megatron_to_transformers[op_name] a : List[str] = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": a : Dict = megatron_to_transformers[op_name] a : Optional[Any] = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. a : str = transformer['final_layernorm.weight'] a : List[str] = transformer['final_layernorm.bias'] # For LM head, transformers' wants the matrix to weight embeddings. a : Optional[int] = word_embeddings # It should be done! return output_state_dict def lowerCamelCase__ ( ): # Create the argument parser. a : Dict = argparse.ArgumentParser() parser.add_argument('--print-checkpoint-structure' , action='store_true' ) parser.add_argument( 'path_to_checkpoint' , type=_A , help='Path to the checkpoint file (.zip archive or direct .pt file)' , ) parser.add_argument( '--config_file' , default='' , type=_A , help='An optional config json file describing the pre-trained model.' , ) a : Union[str, Any] = parser.parse_args() # Extract the basename. a : Optional[Any] = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f"""Extracting PyTorch state dictionary from {args.path_to_checkpoint}""" ) if args.path_to_checkpoint.endswith('.zip' ): with zipfile.ZipFile(args.path_to_checkpoint , 'r' ) as checkpoint: with checkpoint.open('release/mp_rank_00/model_optim_rng.pt' ) as pytorch_dict: a : Union[str, Any] = torch.load(_A , map_location='cpu' ) else: a : Any = torch.load(args.path_to_checkpoint , map_location='cpu' ) a : List[Any] = input_state_dict.get('args' , _A ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: a : int = 'gelu_fast' elif ds_args.openai_gelu: a : Dict = 'gelu_new' else: a : Any = 'gelu' else: # in the very early days this used to be "gelu_new" a : Any = 'gelu_new' # Spell out all parameters in case the defaults change. a : Tuple = GPTaConfig( vocab_size=5_0257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=_A , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1E-5 , initializer_range=0.02 , summary_type='cls_index' , summary_use_proj=_A , summary_activation=_A , summary_proj_to_labels=_A , summary_first_dropout=0.1 , scale_attn_weights=_A , use_cache=_A , bos_token_id=5_0256 , eos_token_id=5_0256 , ) else: a : str = GPTaConfig.from_json_file(args.config_file ) a : Any = ['GPT2LMHeadModel'] # Convert. print('Converting' ) a : Union[str, Any] = convert_megatron_checkpoint(_A , _A , _A ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(_A , _A ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: a : Union[str, Any] = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": a : Tuple = 'gpt2' elif tokenizer_type == "PretrainedFromHF": a : List[str] = ds_args.tokenizer_name_or_path else: raise ValueError(f"""Unrecognized tokenizer_type {tokenizer_type}""" ) else: a : Optional[Any] = 'gpt2' a : Tuple = AutoTokenizer.from_pretrained(_A ) a : str = type(_A ).__name__ a : List[str] = tokenizer_class # Store the config to file. print('Saving config' ) config.save_pretrained(_A ) # Save tokenizer based on args print(f"""Adding {tokenizer_class} tokenizer files""" ) tokenizer.save_pretrained(_A ) # Store the state_dict to file. a : Optional[int] = os.path.join(_A , 'pytorch_model.bin' ) print(f"""Saving checkpoint to \"{output_checkpoint_file}\"""" ) torch.save(_A , _A ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
96
0
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( 'compression_format, is_archive' , [ ('7z', True), ('bz2', False), ('gzip', False), ('lz4', False), ('tar', True), ('xz', False), ('zip', True), ('zstd', False), ] , ) def UpperCamelCase__ ( A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , ) -> Optional[Any]: snake_case__ : Union[str, Any] = { '7z': (seven_zip_file, SevenZipExtractor), 'bz2': (bza_file, BzipaExtractor), 'gzip': (gz_file, GzipExtractor), 'lz4': (lza_file, LzaExtractor), 'tar': (tar_file, TarExtractor), 'xz': (xz_file, XzExtractor), 'zip': (zip_file, ZipExtractor), 'zstd': (zstd_file, ZstdExtractor), } snake_case__ , snake_case__ : Union[str, Any] = input_paths_and_base_extractors[compression_format] if input_path is None: snake_case__ : Optional[int] = F"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(A__ ) assert base_extractor.is_extractable(A__ ) snake_case__ : Tuple = tmp_path / ('extracted' if is_archive else 'extracted.txt') base_extractor.extract(A__ , A__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name snake_case__ : int = file_path.read_text(encoding='utf-8' ) else: snake_case__ : str = output_path.read_text(encoding='utf-8' ) snake_case__ : Dict = text_file.read_text(encoding='utf-8' ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( 'compression_format, is_archive' , [ ('7z', True), ('bz2', False), ('gzip', False), ('lz4', False), ('tar', True), ('xz', False), ('zip', True), ('zstd', False), ] , ) def UpperCamelCase__ ( A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , ) -> Dict: snake_case__ : Tuple = { '7z': seven_zip_file, 'bz2': bza_file, 'gzip': gz_file, 'lz4': lza_file, 'tar': tar_file, 'xz': xz_file, 'zip': zip_file, 'zstd': zstd_file, } snake_case__ : List[Any] = input_paths[compression_format] if input_path is None: snake_case__ : List[Any] = F"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(A__ ) snake_case__ : Union[str, Any] = Extractor.infer_extractor_format(A__ ) assert extractor_format is not None snake_case__ : Any = tmp_path / ('extracted' if is_archive else 'extracted.txt') Extractor.extract(A__ , A__ , A__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name snake_case__ : Any = file_path.read_text(encoding='utf-8' ) else: snake_case__ : List[Any] = output_path.read_text(encoding='utf-8' ) snake_case__ : Optional[int] = text_file.read_text(encoding='utf-8' ) assert extracted_file_content == expected_file_content @pytest.fixture def UpperCamelCase__ ( A__ , A__ ) -> Optional[Any]: import tarfile snake_case__ : Optional[Any] = tmp_path / 'data_dot_dot' directory.mkdir() snake_case__ : Union[str, Any] = directory / 'tar_file_with_dot_dot.tar' with tarfile.TarFile(A__ , 'w' ) as f: f.add(A__ , arcname=os.path.join('..' , text_file.name ) ) return path @pytest.fixture def UpperCamelCase__ ( A__ ) -> Union[str, Any]: import tarfile snake_case__ : str = tmp_path / 'data_sym_link' directory.mkdir() snake_case__ : List[str] = directory / 'tar_file_with_sym_link.tar' os.symlink('..' , directory / 'subdir' , target_is_directory=A__ ) with tarfile.TarFile(A__ , 'w' ) as f: f.add(str(directory / 'subdir' ) , arcname='subdir' ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( 'insecure_tar_file, error_log' , [('tar_file_with_dot_dot', 'illegal path'), ('tar_file_with_sym_link', 'Symlink')] , ) def UpperCamelCase__ ( A__ , A__ , A__ , A__ , A__ , A__ ) -> List[Any]: snake_case__ : Optional[int] = { 'tar_file_with_dot_dot': tar_file_with_dot_dot, 'tar_file_with_sym_link': tar_file_with_sym_link, } snake_case__ : List[Any] = insecure_tar_files[insecure_tar_file] snake_case__ : int = tmp_path / 'extracted' TarExtractor.extract(A__ , A__ ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def UpperCamelCase__ ( A__ ) -> List[str]: # We should have less false positives than zipfile.is_zipfile # We do that by checking only the magic number snake_case__ : int = tmpdir / 'not_a_zip_file' # From: https://github.com/python/cpython/pull/5053 snake_case__ : Union[str, Any] = ( b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00' b'\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6\'\x00\x00\x00\x15I' b'DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07' b'\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82' ) with not_a_zip_file.open('wb' ) as f: f.write(A__ ) assert zipfile.is_zipfile(str(A__ ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(A__ ) # but we're right
143
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase__ : List[str] = { '''configuration_speecht5''': [ '''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''', '''SpeechT5Config''', '''SpeechT5HifiGanConfig''', ], '''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''], '''processing_speecht5''': ['''SpeechT5Processor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : str = ['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : str = [ '''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SpeechT5ForSpeechToText''', '''SpeechT5ForSpeechToSpeech''', '''SpeechT5ForTextToSpeech''', '''SpeechT5Model''', '''SpeechT5PreTrainedModel''', '''SpeechT5HifiGan''', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase__ : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
143
1
from ...processing_utils import ProcessorMixin class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """SpeechT5FeatureExtractor""" UpperCamelCase_ = """SpeechT5Tokenizer""" def __init__( self : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' super().__init__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self : str , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = kwargs.pop('''audio''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = kwargs.pop('''text''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = kwargs.pop('''text_target''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = kwargs.pop('''audio_target''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = kwargs.pop('''sampling_rate''' , UpperCamelCase__ ) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''' ) if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''' ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''' ) if audio is not None: SCREAMING_SNAKE_CASE : Dict = self.feature_extractor(UpperCamelCase__ , *UpperCamelCase__ , sampling_rate=UpperCamelCase__ , **UpperCamelCase__ ) elif text is not None: SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(UpperCamelCase__ , **UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = None if audio_target is not None: SCREAMING_SNAKE_CASE : List[Any] = self.feature_extractor(audio_target=UpperCamelCase__ , *UpperCamelCase__ , sampling_rate=UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = targets['''input_values'''] elif text_target is not None: SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE : List[str] = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE : Tuple = labels SCREAMING_SNAKE_CASE : Optional[Any] = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE : Any = decoder_attention_mask return inputs def __A ( self : Dict , *UpperCamelCase__ : Any , **UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = kwargs.pop('''input_values''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop('''input_ids''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = kwargs.pop('''labels''' , UpperCamelCase__ ) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''' ) if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''' ) if input_values is not None: SCREAMING_SNAKE_CASE : int = self.feature_extractor.pad(UpperCamelCase__ , *UpperCamelCase__ , **UpperCamelCase__ ) elif input_ids is not None: SCREAMING_SNAKE_CASE : Any = self.tokenizer.pad(UpperCamelCase__ , **UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = None if labels is not None: if "input_ids" in labels or (isinstance(UpperCamelCase__ , UpperCamelCase__ ) and "input_ids" in labels[0]): SCREAMING_SNAKE_CASE : int = self.tokenizer.pad(UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extractor.feature_size SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extractor.num_mel_bins SCREAMING_SNAKE_CASE : List[Any] = self.feature_extractor.pad(UpperCamelCase__ , *UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = feature_size_hack SCREAMING_SNAKE_CASE : Any = targets['''input_values'''] else: SCREAMING_SNAKE_CASE : List[str] = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE : List[Any] = labels SCREAMING_SNAKE_CASE : Dict = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE : Any = decoder_attention_mask return inputs def __A ( self : Dict , *UpperCamelCase__ : str , **UpperCamelCase__ : str ): '''simple docstring''' return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : Any ): '''simple docstring''' return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ )
258
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() __UpperCamelCase : Dict = logging.get_logger(__name__) def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Optional[int] = UniSpeechSatForSequenceClassification.from_pretrained(_lowercase , config=_lowercase ) SCREAMING_SNAKE_CASE : Any = downstream_dict['''projector.weight'''] SCREAMING_SNAKE_CASE : Optional[int] = downstream_dict['''projector.bias'''] SCREAMING_SNAKE_CASE : Optional[Any] = downstream_dict['''model.post_net.linear.weight'''] SCREAMING_SNAKE_CASE : int = downstream_dict['''model.post_net.linear.bias'''] return model def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Optional[int] = UniSpeechSatForAudioFrameClassification.from_pretrained(_lowercase , config=_lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = downstream_dict['''model.linear.weight'''] SCREAMING_SNAKE_CASE : str = downstream_dict['''model.linear.bias'''] return model def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : str = UniSpeechSatForXVector.from_pretrained(_lowercase , config=_lowercase ) SCREAMING_SNAKE_CASE : str = downstream_dict['''connector.weight'''] SCREAMING_SNAKE_CASE : Dict = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): SCREAMING_SNAKE_CASE : Optional[Any] = downstream_dict[ f"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] SCREAMING_SNAKE_CASE : List[str] = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] SCREAMING_SNAKE_CASE : int = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] SCREAMING_SNAKE_CASE : Any = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] SCREAMING_SNAKE_CASE : Tuple = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] SCREAMING_SNAKE_CASE : List[str] = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] SCREAMING_SNAKE_CASE : Any = downstream_dict['''objective.W'''] return model @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : List[Any] = torch.load(_lowercase , map_location='''cpu''' ) SCREAMING_SNAKE_CASE : Any = checkpoint['''Downstream'''] SCREAMING_SNAKE_CASE : List[Any] = UniSpeechSatConfig.from_pretrained(_lowercase ) SCREAMING_SNAKE_CASE : int = WavaVecaFeatureExtractor.from_pretrained( _lowercase , return_attention_mask=_lowercase , do_normalize=_lowercase ) SCREAMING_SNAKE_CASE : Tuple = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): SCREAMING_SNAKE_CASE : str = convert_classification(_lowercase , _lowercase , _lowercase ) elif arch.endswith('''ForAudioFrameClassification''' ): SCREAMING_SNAKE_CASE : List[Any] = convert_diarization(_lowercase , _lowercase , _lowercase ) elif arch.endswith('''ForXVector''' ): SCREAMING_SNAKE_CASE : int = convert_xvector(_lowercase , _lowercase , _lowercase ) else: raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: SCREAMING_SNAKE_CASE : int = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(_lowercase ) hf_model.save_pretrained(_lowercase ) if __name__ == "__main__": __UpperCamelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') __UpperCamelCase : Union[str, Any] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
258
1
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase=1_2 , _UpperCamelCase=7 , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=9_9 , _UpperCamelCase=3_2 , _UpperCamelCase=3_2 , _UpperCamelCase=2 , _UpperCamelCase=4 , _UpperCamelCase=3_7 , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=5_1_2 , _UpperCamelCase=0.02 , _UpperCamelCase=0 , _UpperCamelCase=None , ) -> int: UpperCAmelCase_ : Dict = parent UpperCAmelCase_ : int = batch_size UpperCAmelCase_ : Optional[Any] = seq_length UpperCAmelCase_ : List[str] = is_training UpperCAmelCase_ : Tuple = use_input_mask UpperCAmelCase_ : List[str] = use_labels UpperCAmelCase_ : Union[str, Any] = vocab_size UpperCAmelCase_ : List[Any] = hidden_size UpperCAmelCase_ : Any = projection_dim UpperCAmelCase_ : Optional[int] = num_hidden_layers UpperCAmelCase_ : Any = num_attention_heads UpperCAmelCase_ : Tuple = intermediate_size UpperCAmelCase_ : Dict = dropout UpperCAmelCase_ : Tuple = attention_dropout UpperCAmelCase_ : Optional[Any] = max_position_embeddings UpperCAmelCase_ : Any = initializer_range UpperCAmelCase_ : List[Any] = scope UpperCAmelCase_ : int = bos_token_id def __UpperCAmelCase ( self ) -> Optional[Any]: UpperCAmelCase_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Tuple = None if self.use_input_mask: UpperCAmelCase_ : Any = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: UpperCAmelCase_ : List[str] = input_mask.numpy() UpperCAmelCase_ , UpperCAmelCase_ : Any = input_mask.shape UpperCAmelCase_ : int = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__UpperCamelCase ): UpperCAmelCase_ : str = 1 UpperCAmelCase_ : Optional[Any] = 0 UpperCAmelCase_ : Tuple = self.get_config() return config, input_ids, tf.convert_to_tensor(__UpperCamelCase ) def __UpperCAmelCase ( self ) -> List[str]: return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: UpperCAmelCase_ : Dict = TFBlipTextModel(config=__UpperCamelCase ) UpperCAmelCase_ : str = model(__UpperCamelCase , attention_mask=__UpperCamelCase , training=__UpperCamelCase ) UpperCAmelCase_ : int = model(__UpperCamelCase , training=__UpperCamelCase ) 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[Any]: UpperCAmelCase_ : List[str] = self.prepare_config_and_inputs() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = config_and_inputs UpperCAmelCase_ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowerCamelCase (_lowercase , unittest.TestCase ): '''simple docstring''' _snake_case : str = (TFBlipTextModel,) if is_tf_available() else () _snake_case : int = False _snake_case : Optional[Any] = False _snake_case : int = False def __UpperCAmelCase ( self ) -> List[str]: UpperCAmelCase_ : List[Any] = BlipTextModelTester(self ) UpperCAmelCase_ : str = ConfigTester(self , config_class=__UpperCamelCase , hidden_size=3_7 ) def __UpperCAmelCase ( self ) -> Dict: self.config_tester.run_common_tests() def __UpperCAmelCase ( self ) -> str: UpperCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase ) def __UpperCAmelCase ( self ) -> Tuple: pass def __UpperCAmelCase ( self ) -> Optional[int]: pass @unittest.skip(reason='Blip does not use inputs_embeds' ) def __UpperCAmelCase ( self ) -> List[Any]: pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def __UpperCAmelCase ( self ) -> Optional[Any]: pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def __UpperCAmelCase ( self ) -> Any: pass @slow def __UpperCAmelCase ( self ) -> Optional[int]: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : str = TFBlipTextModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) def __UpperCAmelCase ( self , _UpperCamelCase=True ) -> Union[str, Any]: super().test_pt_tf_model_equivalence(allow_missing_keys=__UpperCamelCase )
29
"""simple docstring""" def lowercase ( a__ : float , a__ : float ) -> float: if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
256
0
"""simple docstring""" def lowerCamelCase_ (UpperCamelCase__ : Optional[int] = 100_0000 ): _UpperCAmelCase : str = 1 _UpperCAmelCase : Dict = 1 _UpperCAmelCase : Dict = {1: 1} for inputa in range(2 , _lowerCAmelCase ): _UpperCAmelCase : Optional[int] = 0 _UpperCAmelCase : Any = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: _UpperCAmelCase : Optional[int] = (3 * number) + 1 counter += 1 if inputa not in counters: _UpperCAmelCase : Tuple = counter if counter > pre_counter: _UpperCAmelCase : Optional[Any] = inputa _UpperCAmelCase : List[Any] = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
354
"""simple docstring""" import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger _lowerCAmelCase :int = get_logger(__name__) class _UpperCAmelCase ( enum.Enum ): '''simple docstring''' a__ ='''all_checks''' a__ ='''basic_checks''' a__ ='''no_checks''' class _UpperCAmelCase ( a ): '''simple docstring''' class _UpperCAmelCase ( a ): '''simple docstring''' class _UpperCAmelCase ( a ): '''simple docstring''' class _UpperCAmelCase ( a ): '''simple docstring''' def lowerCamelCase_ (UpperCamelCase__ : Optional[dict] , UpperCamelCase__ : dict , UpperCamelCase__ : Tuple=None ): if expected_checksums is None: logger.info('''Unable to verify checksums.''' ) return if len(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) ) if len(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) > 0: raise UnexpectedDownloadedFile(str(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) ) _UpperCAmelCase : Optional[Any] = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] _UpperCAmelCase : str = ''' for ''' + verification_name if verification_name is not None else '''''' if len(UpperCamelCase__ ) > 0: raise NonMatchingChecksumError( F'Checksums didn\'t match{for_verification_name}:\n' F'{bad_urls}\n' '''Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error''' ) logger.info('''All the checksums matched successfully''' + for_verification_name ) class _UpperCAmelCase ( a ): '''simple docstring''' class _UpperCAmelCase ( a ): '''simple docstring''' class _UpperCAmelCase ( a ): '''simple docstring''' class _UpperCAmelCase ( a ): '''simple docstring''' def lowerCamelCase_ (UpperCamelCase__ : Optional[dict] , UpperCamelCase__ : dict ): if expected_splits is None: logger.info('''Unable to verify splits sizes.''' ) return if len(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) > 0: raise ExpectedMoreSplits(str(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) ) if len(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) > 0: raise UnexpectedSplits(str(set(UpperCamelCase__ ) - set(UpperCamelCase__ ) ) ) _UpperCAmelCase : Dict = [ {'''expected''': expected_splits[name], '''recorded''': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(UpperCamelCase__ ) > 0: raise NonMatchingSplitsSizesError(str(UpperCamelCase__ ) ) logger.info('''All the splits matched successfully.''' ) def lowerCamelCase_ (UpperCamelCase__ : str , UpperCamelCase__ : bool = True ): if record_checksum: _UpperCAmelCase : Any = shaaaa() with open(UpperCamelCase__ , '''rb''' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B'''''' ): m.update(UpperCamelCase__ ) _UpperCAmelCase : int = m.hexdigest() else: _UpperCAmelCase : Union[str, Any] = None return {"num_bytes": os.path.getsize(UpperCamelCase__ ), "checksum": checksum} def lowerCamelCase_ (UpperCamelCase__ : List[str] ): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
68
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list[int]: __a = [0 for i in range(len(lowerCAmelCase__ ) )] # initialize interval's left pointer and right pointer __a , __a = 0, 0 for i in range(1 , len(lowerCAmelCase__ ) ): # case when current index is inside the interval if i <= right_pointer: __a = min(right_pointer - i + 1 , z_result[i - left_pointer] ) __a = min_edge while go_next(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: __a , __a = i, i + z_result[i] - 1 return z_result def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : str ) -> bool: return i + z_result[i] < len(lowerCAmelCase__ ) and s[z_result[i]] == s[i + z_result[i]] def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> int: __a = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string __a = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(lowerCAmelCase__ ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[int] , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : int ) -> None: if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): UpperCAmelCase_ , UpperCAmelCase_ = array[indexa], array[indexa] def SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[int] , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : int ) -> None: if length > 1: UpperCAmelCase_ = int(length / 2 ) for i in range(__UpperCamelCase , low + middle ): comp_and_swap(__UpperCamelCase , __UpperCamelCase , i + middle , __UpperCamelCase ) bitonic_merge(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) bitonic_merge(__UpperCamelCase , low + middle , __UpperCamelCase , __UpperCamelCase ) def SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[int] , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : int ) -> None: if length > 1: UpperCAmelCase_ = int(length / 2 ) bitonic_sort(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , 1 ) bitonic_sort(__UpperCamelCase , low + middle , __UpperCamelCase , 0 ) bitonic_merge(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": _lowerCamelCase = input('Enter numbers separated by a comma:\n').strip() _lowerCamelCase = [int(item.strip()) for item in user_input.split(',')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('\nSorted array in ascending order is: ', end='') print(*unsorted, sep=', ') bitonic_merge(unsorted, 0, len(unsorted), 0) print('Sorted array in descending order is: ', end='') print(*unsorted, sep=', ')
353
from __future__ import annotations import os from collections.abc import Mapping _lowerCamelCase = tuple[int, int] class a : '''simple docstring''' def __init__( self : str , __snake_case : set[int] , __snake_case : Mapping[EdgeT, int] ): UpperCAmelCase_ = vertices UpperCAmelCase_ = { (min(__snake_case ), max(__snake_case )): weight for edge, weight in edges.items() } def lowerCamelCase_ ( self : Any , __snake_case : EdgeT , __snake_case : int ): self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) UpperCAmelCase_ = weight def lowerCamelCase_ ( self : Union[str, Any] ): UpperCAmelCase_ = Graph({min(self.vertices )} , {} ) UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 while len(subgraph.vertices ) < len(self.vertices ): UpperCAmelCase_ = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: UpperCAmelCase_ = edge UpperCAmelCase_ = weight subgraph.add_edge(__snake_case , __snake_case ) return subgraph def SCREAMING_SNAKE_CASE ( __UpperCamelCase : str = "p107_network.txt" ) -> int: UpperCAmelCase_ = os.path.abspath(os.path.dirname(__UpperCamelCase ) ) UpperCAmelCase_ = os.path.join(__UpperCamelCase , __UpperCamelCase ) UpperCAmelCase_ = {} UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 with open(__UpperCamelCase ) as f: UpperCAmelCase_ = f.read().strip().split('''\n''' ) UpperCAmelCase_ = [line.split(''',''' ) for line in data] for edgea in range(1 , len(__UpperCamelCase ) ): for edgea in range(__UpperCamelCase ): if adjaceny_matrix[edgea][edgea] != "-": UpperCAmelCase_ = int(adjaceny_matrix[edgea][edgea] ) UpperCAmelCase_ = Graph(set(range(len(__UpperCamelCase ) ) ) , __UpperCamelCase ) UpperCAmelCase_ = graph.prims_algorithm() UpperCAmelCase_ = sum(graph.edges.values() ) UpperCAmelCase_ = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
177
0
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @register_to_config def __init__( self, lowerCamelCase__ = 32, lowerCamelCase__ = 64, lowerCamelCase__ = 20, lowerCamelCase__ = 768, lowerCamelCase__=77, lowerCamelCase__=4, lowerCamelCase__ = 0.0, lowerCamelCase__ = "silu", lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = "linear", lowerCamelCase__ = "prd", lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = None, ): super().__init__() A : int = num_attention_heads A : Tuple = attention_head_dim A : Optional[int] = num_attention_heads * attention_head_dim A : List[str] = additional_embeddings A : int = time_embed_dim or inner_dim A : Tuple = embedding_proj_dim or embedding_dim A : Dict = clip_embed_dim or embedding_dim A : List[str] = Timesteps(lowerCamelCase__, lowerCamelCase__, 0 ) A : Any = TimestepEmbedding(lowerCamelCase__, lowerCamelCase__, out_dim=lowerCamelCase__, act_fn=lowerCamelCase__ ) A : List[Any] = nn.Linear(lowerCamelCase__, lowerCamelCase__ ) if embedding_proj_norm_type is None: A : Union[str, Any] = None elif embedding_proj_norm_type == "layer": A : str = nn.LayerNorm(lowerCamelCase__ ) else: raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) A : Optional[Any] = nn.Linear(lowerCamelCase__, lowerCamelCase__ ) if encoder_hid_proj_type is None: A : Dict = None elif encoder_hid_proj_type == "linear": A : Union[str, Any] = nn.Linear(lowerCamelCase__, lowerCamelCase__ ) else: raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) A : List[str] = nn.Parameter(torch.zeros(1, num_embeddings + additional_embeddings, lowerCamelCase__ ) ) if added_emb_type == "prd": A : Union[str, Any] = nn.Parameter(torch.zeros(1, 1, lowerCamelCase__ ) ) elif added_emb_type is None: A : int = None else: raise ValueError( f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) A : int = nn.ModuleList( [ BasicTransformerBlock( lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, dropout=lowerCamelCase__, activation_fn="""gelu""", attention_bias=lowerCamelCase__, ) for d in range(lowerCamelCase__ ) ] ) if norm_in_type == "layer": A : int = nn.LayerNorm(lowerCamelCase__ ) elif norm_in_type is None: A : Tuple = None else: raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.''' ) A : Optional[Any] = nn.LayerNorm(lowerCamelCase__ ) A : str = nn.Linear(lowerCamelCase__, lowerCamelCase__ ) A : Union[str, Any] = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings], -1_0000.0 ) causal_attention_mask.triu_(1 ) A : Optional[Any] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""", lowerCamelCase__, persistent=lowerCamelCase__ ) A : Dict = nn.Parameter(torch.zeros(1, lowerCamelCase__ ) ) A : Tuple = nn.Parameter(torch.zeros(1, lowerCamelCase__ ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def _lowerCAmelCase ( self ): A : Optional[int] = {} def fn_recursive_add_processors(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ): if hasattr(lowerCamelCase__, """set_processor""" ): A : Tuple = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'''{name}.{sub_name}''', lowerCamelCase__, lowerCamelCase__ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) return processors def _lowerCAmelCase ( self, lowerCamelCase__ ): A : Optional[Any] = len(self.attn_processors.keys() ) if isinstance(lowerCamelCase__, lowerCamelCase__ ) and len(lowerCamelCase__ ) != count: raise ValueError( f'''A dict of processors was passed, but the number of processors {len(lowerCamelCase__ )} does not match the''' f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ): if hasattr(lowerCamelCase__, """set_processor""" ): if not isinstance(lowerCamelCase__, lowerCamelCase__ ): module.set_processor(lowerCamelCase__ ) else: module.set_processor(processor.pop(f'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f'''{name}.{sub_name}''', lowerCamelCase__, lowerCamelCase__ ) for name, module in self.named_children(): fn_recursive_attn_processor(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self ): self.set_attn_processor(AttnProcessor() ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = True, ): A : Optional[int] = hidden_states.shape[0] A : Tuple = timestep if not torch.is_tensor(lowerCamelCase__ ): A : List[Any] = torch.tensor([timesteps], dtype=torch.long, device=hidden_states.device ) elif torch.is_tensor(lowerCamelCase__ ) and len(timesteps.shape ) == 0: A : Optional[int] = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML A : Optional[Any] = timesteps * torch.ones(lowerCamelCase__, dtype=timesteps.dtype, device=timesteps.device ) A : str = self.time_proj(lowerCamelCase__ ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. A : Union[str, Any] = timesteps_projected.to(dtype=self.dtype ) A : Tuple = self.time_embedding(lowerCamelCase__ ) if self.embedding_proj_norm is not None: A : Optional[Any] = self.embedding_proj_norm(lowerCamelCase__ ) A : Any = self.embedding_proj(lowerCamelCase__ ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: A : List[str] = self.encoder_hidden_states_proj(lowerCamelCase__ ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) A : Tuple = self.proj_in(lowerCamelCase__ ) A : Dict = self.positional_embedding.to(hidden_states.dtype ) A : List[str] = [] A : Optional[Any] = 0 if encoder_hidden_states is not None: additional_embeds.append(lowerCamelCase__ ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: A : Optional[Any] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: A : List[str] = hidden_states[:, None, :] A : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: A : List[Any] = self.prd_embedding.to(hidden_states.dtype ).expand(lowerCamelCase__, -1, -1 ) additional_embeds.append(lowerCamelCase__ ) A : Union[str, Any] = torch.cat( lowerCamelCase__, dim=1, ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens A : Dict = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: A : Any = F.pad( lowerCamelCase__, ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ), value=0.0, ) A : Union[str, Any] = hidden_states + positional_embeddings if attention_mask is not None: A : List[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -1_0000.0 A : Tuple = F.pad(lowerCamelCase__, (0, self.additional_embeddings), value=0.0 ) A : List[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) A : Any = attention_mask.repeat_interleave(self.config.num_attention_heads, dim=0 ) if self.norm_in is not None: A : str = self.norm_in(lowerCamelCase__ ) for block in self.transformer_blocks: A : Optional[Any] = block(lowerCamelCase__, attention_mask=lowerCamelCase__ ) A : Optional[int] = self.norm_out(lowerCamelCase__ ) if self.prd_embedding is not None: A : Dict = hidden_states[:, -1] else: A : Optional[int] = hidden_states[:, additional_embeddings_len:] A : Optional[Any] = self.proj_to_clip_embeddings(lowerCamelCase__ ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__ ): A : str = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
116
import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class SCREAMING_SNAKE_CASE__ ( tf.keras.optimizers.schedules.LearningRateSchedule ): '''simple docstring''' def __init__( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ = 1.0, lowerCamelCase__ = None, ): super().__init__() A : Union[str, Any] = initial_learning_rate A : List[Any] = warmup_steps A : int = power A : Optional[int] = decay_schedule_fn A : int = name def __call__( self, lowerCamelCase__ ): with tf.name_scope(self.name or """WarmUp""" ) as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. A : str = tf.cast(lowerCamelCase__, tf.floataa ) A : List[Any] = tf.cast(self.warmup_steps, tf.floataa ) A : Dict = global_step_float / warmup_steps_float A : Union[str, Any] = self.initial_learning_rate * tf.math.pow(lowerCamelCase__, self.power ) return tf.cond( global_step_float < warmup_steps_float, lambda: warmup_learning_rate, lambda: self.decay_schedule_fn(step - self.warmup_steps ), name=lowerCamelCase__, ) def _lowerCAmelCase ( self ): return { "initial_learning_rate": self.initial_learning_rate, "decay_schedule_fn": self.decay_schedule_fn, "warmup_steps": self.warmup_steps, "power": self.power, "name": self.name, } def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 0.0 , _lowerCAmelCase = 0.9 , _lowerCAmelCase = 0.999 , _lowerCAmelCase = 1e-8 , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = 0.0 , _lowerCAmelCase = 1.0 , _lowerCAmelCase = None , ) -> Union[str, Any]: """simple docstring""" A : Optional[int] = tf.keras.optimizers.schedules.PolynomialDecay( initial_learning_rate=_lowerCAmelCase , decay_steps=num_train_steps - num_warmup_steps , end_learning_rate=init_lr * min_lr_ratio , power=_lowerCAmelCase , ) if num_warmup_steps: A : Dict = WarmUp( initial_learning_rate=_lowerCAmelCase , decay_schedule_fn=_lowerCAmelCase , warmup_steps=_lowerCAmelCase , ) if weight_decay_rate > 0.0: A : str = AdamWeightDecay( learning_rate=_lowerCAmelCase , weight_decay_rate=_lowerCAmelCase , beta_a=_lowerCAmelCase , beta_a=_lowerCAmelCase , epsilon=_lowerCAmelCase , clipnorm=_lowerCAmelCase , global_clipnorm=_lowerCAmelCase , exclude_from_weight_decay=["""LayerNorm""", """layer_norm""", """bias"""] , include_in_weight_decay=_lowerCAmelCase , ) else: A : Optional[int] = tf.keras.optimizers.Adam( learning_rate=_lowerCAmelCase , beta_a=_lowerCAmelCase , beta_a=_lowerCAmelCase , epsilon=_lowerCAmelCase , clipnorm=_lowerCAmelCase , global_clipnorm=_lowerCAmelCase , ) # We return the optimizer and the LR scheduler in order to better track the # evolution of the LR independently of the optimizer. return optimizer, lr_schedule class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self, lowerCamelCase__ = 0.001, lowerCamelCase__ = 0.9, lowerCamelCase__ = 0.999, lowerCamelCase__ = 1e-7, lowerCamelCase__ = False, lowerCamelCase__ = 0.0, lowerCamelCase__ = None, lowerCamelCase__ = None, lowerCamelCase__ = "AdamWeightDecay", **lowerCamelCase__, ): super().__init__(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__ ) A : int = weight_decay_rate A : Any = include_in_weight_decay A : Dict = exclude_from_weight_decay @classmethod def _lowerCAmelCase ( cls, lowerCamelCase__ ): A : Tuple = {"""WarmUp""": WarmUp} return super(lowerCamelCase__, cls ).from_config(lowerCamelCase__, custom_objects=lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ): super(lowerCamelCase__, self )._prepare_local(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) A : List[str] = tf.constant( self.weight_decay_rate, name="""adam_weight_decay_rate""" ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ): A : Any = self._do_use_weight_decay(var.name ) if do_decay: return var.assign_sub( learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["""weight_decay_rate"""], use_locking=self._use_locking, ) return tf.no_op() def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__=None, **lowerCamelCase__ ): A , A : Dict = list(zip(*lowerCamelCase__ ) ) return super(lowerCamelCase__, self ).apply_gradients(zip(lowerCamelCase__, lowerCamelCase__ ), name=lowerCamelCase__, **lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ): if apply_state is None: return self._decayed_lr_t[var_dtype], {} A : Union[str, Any] = apply_state or {} A : Optional[int] = apply_state.get((var_device, var_dtype) ) if coefficients is None: A : Dict = self._fallback_apply_state(lowerCamelCase__, lowerCamelCase__ ) A : List[Any] = coefficients return coefficients["lr_t"], {"apply_state": apply_state} def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__=None ): A , A : str = self._get_lr(var.device, var.dtype.base_dtype, lowerCamelCase__ ) A : Any = self._decay_weights_op(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) with tf.control_dependencies([decay] ): return super(lowerCamelCase__, self )._resource_apply_dense(lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__ ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__=None ): A , A : Tuple = self._get_lr(var.device, var.dtype.base_dtype, lowerCamelCase__ ) A : Optional[Any] = self._decay_weights_op(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) with tf.control_dependencies([decay] ): return super(lowerCamelCase__, self )._resource_apply_sparse(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : Dict = super().get_config() config.update({"""weight_decay_rate""": self.weight_decay_rate} ) return config def _lowerCAmelCase ( self, lowerCamelCase__ ): if self.weight_decay_rate == 0: return False if self._include_in_weight_decay: for r in self._include_in_weight_decay: if re.search(lowerCamelCase__, lowerCamelCase__ ) is not None: return True if self._exclude_from_weight_decay: for r in self._exclude_from_weight_decay: if re.search(lowerCamelCase__, lowerCamelCase__ ) is not None: return False return True class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self ): A : List[str] = [] A : List[str] = None @property def _lowerCAmelCase ( self ): if self._accum_steps is None: A : str = tf.Variable( tf.constant(0, dtype=tf.intaa ), trainable=lowerCamelCase__, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA, ) return self._accum_steps.value() @property def _lowerCAmelCase ( self ): if not self._gradients: raise ValueError("""The accumulator should be called first to initialize the gradients""" ) return [gradient.value() if gradient is not None else gradient for gradient in self._gradients] def __call__( self, lowerCamelCase__ ): if not self._gradients: A : int = self.step # Create the step variable. self._gradients.extend( [ tf.Variable( tf.zeros_like(lowerCamelCase__ ), trainable=lowerCamelCase__, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA, ) if gradient is not None else gradient for gradient in gradients ] ) if len(lowerCamelCase__ ) != len(self._gradients ): raise ValueError(f'''Expected {len(self._gradients )} gradients, but got {len(lowerCamelCase__ )}''' ) for accum_gradient, gradient in zip(self._gradients, lowerCamelCase__ ): if accum_gradient is not None and gradient is not None: accum_gradient.assign_add(lowerCamelCase__ ) self._accum_steps.assign_add(1 ) def _lowerCAmelCase ( self ): if not self._gradients: return self._accum_steps.assign(0 ) for gradient in self._gradients: if gradient is not None: gradient.assign(tf.zeros_like(lowerCamelCase__ ) )
116
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : 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: _SCREAMING_SNAKE_CASE : Union[str, Any] = ["ConvBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = [ "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: _SCREAMING_SNAKE_CASE : Optional[int] = [ "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 _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
92
'''simple docstring''' import logging import os from .state import PartialState class _snake_case ( logging.LoggerAdapter ): @staticmethod def lowerCAmelCase__ ( a__ ) -> Optional[Any]: '''simple docstring''' snake_case_ = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def lowerCAmelCase__ ( self , a__ , a__ , *a__ , **a__ ) -> List[Any]: '''simple docstring''' if PartialState._shared_state == {}: raise RuntimeError( "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility." ) snake_case_ = kwargs.pop("main_process_only" , a__ ) snake_case_ = kwargs.pop("in_order" , a__ ) if self.isEnabledFor(a__ ): if self._should_log(a__ ): snake_case_ , snake_case_ = self.process(a__ , a__ ) self.logger.log(a__ , a__ , *a__ , **a__ ) elif in_order: snake_case_ = PartialState() for i in range(state.num_processes ): if i == state.process_index: snake_case_ , snake_case_ = self.process(a__ , a__ ) self.logger.log(a__ , a__ , *a__ , **a__ ) state.wait_for_everyone() def UpperCamelCase_( snake_case : str , snake_case : str = None ): '''simple docstring''' if log_level is None: snake_case_ = os.environ.get("ACCELERATE_LOG_LEVEL" , snake_case ) snake_case_ = logging.getLogger(snake_case ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(snake_case , {} )
92
1
"""simple docstring""" import math def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _SCREAMING_SNAKE_CASE (__lowerCAmelCase = 0.1 ) -> int: '''simple docstring''' lowercase_ = 3 lowercase_ = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__lowerCAmelCase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
136
"""simple docstring""" from math import pi, sqrt, tan def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> float: '''simple docstring''' if side_length < 0: raise ValueError("""surface_area_cube() only accepts non-negative values""" ) return 6 * side_length**2 def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if length < 0 or breadth < 0 or height < 0: raise ValueError("""surface_area_cuboid() only accepts non-negative values""" ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> float: '''simple docstring''' if radius < 0: raise ValueError("""surface_area_sphere() only accepts non-negative values""" ) return 4 * pi * radius**2 def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> float: '''simple docstring''' if radius < 0: raise ValueError("""surface_area_hemisphere() only accepts non-negative values""" ) return 3 * pi * radius**2 def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if radius < 0 or height < 0: raise ValueError("""surface_area_cone() only accepts non-negative values""" ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( """surface_area_conical_frustum() only accepts non-negative values""" ) lowercase_ = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if radius < 0 or height < 0: raise ValueError("""surface_area_cylinder() only accepts non-negative values""" ) return 2 * pi * radius * (height + radius) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if torus_radius < 0 or tube_radius < 0: raise ValueError("""surface_area_torus() only accepts non-negative values""" ) if torus_radius < tube_radius: raise ValueError( """surface_area_torus() does not support spindle or self intersecting tori""" ) return 4 * pow(__lowerCAmelCase , 2 ) * torus_radius * tube_radius def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if length < 0 or width < 0: raise ValueError("""area_rectangle() only accepts non-negative values""" ) return length * width def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> float: '''simple docstring''' if side_length < 0: raise ValueError("""area_square() only accepts non-negative values""" ) return side_length**2 def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if base < 0 or height < 0: raise ValueError("""area_triangle() only accepts non-negative values""" ) return (base * height) / 2 def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError("""area_triangle_three_sides() only accepts non-negative values""" ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError("""Given three sides do not form a triangle""" ) lowercase_ = (sidea + sidea + sidea) / 2 lowercase_ = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if base < 0 or height < 0: raise ValueError("""area_parallelogram() only accepts non-negative values""" ) return base * height def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if basea < 0 or basea < 0 or height < 0: raise ValueError("""area_trapezium() only accepts non-negative values""" ) return 1 / 2 * (basea + basea) * height def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> float: '''simple docstring''' if radius < 0: raise ValueError("""area_circle() only accepts non-negative values""" ) return pi * radius**2 def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if radius_x < 0 or radius_y < 0: raise ValueError("""area_ellipse() only accepts non-negative values""" ) return pi * radius_x * radius_y def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if diagonal_a < 0 or diagonal_a < 0: raise ValueError("""area_rhombus() only accepts non-negative values""" ) return 1 / 2 * diagonal_a * diagonal_a def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> float: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or sides < 3: raise ValueError( """area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides""" ) elif length < 0: raise ValueError( """area_reg_polygon() only accepts non-negative values as \ length of a side""" ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print("[DEMO] Areas of various geometric shapes: \n") print(F"Rectangle: {area_rectangle(10, 20) = }") print(F"Square: {area_square(10) = }") print(F"Triangle: {area_triangle(10, 10) = }") print(F"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(F"Parallelogram: {area_parallelogram(10, 20) = }") print(F"Rhombus: {area_rhombus(10, 20) = }") print(F"Trapezium: {area_trapezium(10, 20, 30) = }") print(F"Circle: {area_circle(20) = }") print(F"Ellipse: {area_ellipse(10, 20) = }") print("\nSurface Areas of various geometric shapes: \n") print(F"Cube: {surface_area_cube(20) = }") print(F"Cuboid: {surface_area_cuboid(10, 20, 30) = }") print(F"Sphere: {surface_area_sphere(20) = }") print(F"Hemisphere: {surface_area_hemisphere(20) = }") print(F"Cone: {surface_area_cone(10, 20) = }") print(F"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") print(F"Cylinder: {surface_area_cylinder(10, 20) = }") print(F"Torus: {surface_area_torus(20, 10) = }") print(F"Equilateral Triangle: {area_reg_polygon(3, 10) = }") print(F"Square: {area_reg_polygon(4, 10) = }") print(F"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
136
1
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCamelCase ( A_ ): UpperCAmelCase__ : Any = (KDPMaDiscreteScheduler,) UpperCAmelCase__ : Any = 10 def UpperCAmelCase(self : int , **_A : Tuple ) -> str: snake_case = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**_A ) return config def UpperCAmelCase(self : Union[str, Any] ) -> Optional[Any]: for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_A ) def UpperCAmelCase(self : Optional[int] ) -> Any: 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=_A , beta_end=_A ) def UpperCAmelCase(self : int ) -> Union[str, Any]: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_A ) def UpperCAmelCase(self : int ) -> Union[str, Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def UpperCAmelCase(self : List[Any] ) -> str: snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config(prediction_type="v_prediction" ) snake_case = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) snake_case = self.dummy_model() snake_case = self.dummy_sample_deter * scheduler.init_noise_sigma snake_case = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): snake_case = scheduler.scale_model_input(_A , _A ) snake_case = model(_A , _A ) snake_case = scheduler.step(_A , _A , _A ) snake_case = output.prev_sample snake_case = torch.sum(torch.abs(_A ) ) snake_case = torch.mean(torch.abs(_A ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.69_34E-07 ) < 1E-2 assert abs(result_mean.item() - 6.11_12E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.6_93_42_86_50_17_09_72E-07 ) < 1E-2 assert abs(result_mean.item() - 0.00_02 ) < 1E-3 def UpperCAmelCase(self : Union[str, Any] ) -> Optional[Any]: if torch_device == "mps": return snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) snake_case = self.dummy_model() snake_case = self.dummy_sample_deter * scheduler.init_noise_sigma snake_case = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): snake_case = scheduler.scale_model_input(_A , _A ) snake_case = model(_A , _A ) snake_case = scheduler.step(_A , _A , _A ) snake_case = output.prev_sample snake_case = torch.sum(torch.abs(_A ) ) snake_case = torch.mean(torch.abs(_A ) ) 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 UpperCAmelCase(self : Optional[int] ) -> Tuple: if torch_device == "mps": return snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) snake_case = self.dummy_model() snake_case = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma for t in scheduler.timesteps: snake_case = scheduler.scale_model_input(_A , _A ) snake_case = model(_A , _A ) snake_case = scheduler.step(_A , _A , _A ) snake_case = output.prev_sample snake_case = torch.sum(torch.abs(_A ) ) snake_case = torch.mean(torch.abs(_A ) ) if str(_A ).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
137
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer _A = logging.get_logger(__name__) _A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _A = { "vocab_file": {"mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt"}, "tokenizer_file": { "mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json" }, } _A = {"mobilebert-uncased": 5_12} _A = {} class lowerCamelCase ( A_ ): UpperCAmelCase__ : Tuple = VOCAB_FILES_NAMES UpperCAmelCase__ : Any = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : Optional[Any] = MobileBertTokenizer def __init__(self : Any , _A : str=None , _A : str=None , _A : Union[str, Any]=True , _A : Optional[Any]="[UNK]" , _A : int="[SEP]" , _A : Dict="[PAD]" , _A : int="[CLS]" , _A : Union[str, Any]="[MASK]" , _A : Any=True , _A : Dict=None , **_A : List[str] , ) -> List[str]: super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) snake_case = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , _A ) != do_lower_case or normalizer_state.get("strip_accents" , _A ) != strip_accents or normalizer_state.get("handle_chinese_chars" , _A ) != tokenize_chinese_chars ): snake_case = getattr(_A , normalizer_state.pop("type" ) ) snake_case = do_lower_case snake_case = strip_accents snake_case = tokenize_chinese_chars snake_case = normalizer_class(**_A ) snake_case = do_lower_case def UpperCAmelCase(self : List[str] , _A : Union[str, Any] , _A : Dict=None ) -> Optional[Any]: 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 UpperCAmelCase(self : Union[str, Any] , _A : List[int] , _A : Optional[List[int]] = None ) -> List[int]: 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 UpperCAmelCase(self : int , _A : str , _A : Optional[str] = None ) -> Tuple[str]: snake_case = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
137
1
import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def a__ ( snake_case , snake_case , snake_case , snake_case=1_024 ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Any = [], [] __SCREAMING_SNAKE_CASE : List[str] = list(zip(snake_case_ , snake_case_ ) ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = sorted_examples[0] def is_too_big(snake_case ): return tok(snake_case_ , return_tensors='''pt''' ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): __SCREAMING_SNAKE_CASE : str = new_src + ''' ''' + src __SCREAMING_SNAKE_CASE : List[str] = new_tgt + ''' ''' + tgt if is_too_big(snake_case_ ) or is_too_big(snake_case_ ): # cant fit, finalize example finished_src.append(snake_case_ ) finished_tgt.append(snake_case_ ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = src, tgt else: # can fit, keep adding __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(snake_case_ ) finished_tgt.append(snake_case_ ) return finished_src, finished_tgt def a__ ( snake_case , snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = Path(snake_case_ ) save_path.mkdir(exist_ok=snake_case_ ) for split in ["train"]: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = data_dir / F'''{split}.source''', data_dir / F'''{split}.target''' __SCREAMING_SNAKE_CASE : Any = [x.rstrip() for x in Path(snake_case_ ).open().readlines()] __SCREAMING_SNAKE_CASE : List[Any] = [x.rstrip() for x in Path(snake_case_ ).open().readlines()] __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = pack_examples(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) print(F'''packed {split} split from {len(snake_case_ )} examples -> {len(snake_case_ )}.''' ) Path(save_path / F'''{split}.source''' ).open('''w''' ).write('''\n'''.join(snake_case_ ) ) Path(save_path / F'''{split}.target''' ).open('''w''' ).write('''\n'''.join(snake_case_ ) ) for split in ["val", "test"]: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Any = data_dir / F'''{split}.source''', data_dir / F'''{split}.target''' shutil.copyfile(snake_case_ , save_path / F'''{split}.source''' ) shutil.copyfile(snake_case_ , save_path / F'''{split}.target''' ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser() parser.add_argument('''--tok_name''' , type=snake_case_ , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''--max_seq_len''' , type=snake_case_ , default=128 ) parser.add_argument('''--data_dir''' , type=snake_case_ ) parser.add_argument('''--save_path''' , type=snake_case_ ) __SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() __SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(snake_case_ , Path(args.data_dir ) , args.max_seq_len , args.save_path ) if __name__ == "__main__": packer_cli()
303
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ : str = logging.get_logger(__name__) lowercase_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowercase_ : Optional[Any] = { 'vocab_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/vocab.json', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/vocab.json', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/vocab.json', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/vocab.json', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/vocab.json', }, 'merges_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/merges.txt', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/merges.txt', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/merges.txt', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/merges.txt', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/merges.txt', }, 'tokenizer_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/tokenizer.json', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/tokenizer.json', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/tokenizer.json', }, } lowercase_ : int = { 'gpt2': 10_24, 'gpt2-medium': 10_24, 'gpt2-large': 10_24, 'gpt2-xl': 10_24, 'distilgpt2': 10_24, } class __lowerCAmelCase ( UpperCAmelCase__ ): snake_case_ : Optional[int] = VOCAB_FILES_NAMES snake_case_ : List[str] = PRETRAINED_VOCAB_FILES_MAP snake_case_ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ : Tuple = ["input_ids", "attention_mask"] snake_case_ : str = GPTaTokenizer def __init__( self : List[str] , snake_case__ : Any=None , snake_case__ : List[Any]=None , snake_case__ : Union[str, Any]=None , snake_case__ : List[str]="<|endoftext|>" , snake_case__ : str="<|endoftext|>" , snake_case__ : Optional[int]="<|endoftext|>" , snake_case__ : str=False , **snake_case__ : Dict , ): """simple docstring""" super().__init__( snake_case__ , snake_case__ , tokenizer_file=snake_case__ , unk_token=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , add_prefix_space=snake_case__ , **snake_case__ , ) _UpperCAmelCase = kwargs.pop("add_bos_token" , snake_case__ ) _UpperCAmelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , snake_case__ ) != add_prefix_space: _UpperCAmelCase = getattr(snake_case__ , pre_tok_state.pop("type" ) ) _UpperCAmelCase = add_prefix_space _UpperCAmelCase = pre_tok_class(**snake_case__ ) _UpperCAmelCase = add_prefix_space def UpperCamelCase ( self : Union[str, Any] , *snake_case__ : int , **snake_case__ : Union[str, Any] ): """simple docstring""" _UpperCAmelCase = kwargs.get("is_split_into_words" , snake_case__ ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*snake_case__ , **snake_case__ ) def UpperCamelCase ( self : int , *snake_case__ : Optional[Any] , **snake_case__ : List[str] ): """simple docstring""" _UpperCAmelCase = kwargs.get("is_split_into_words" , snake_case__ ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*snake_case__ , **snake_case__ ) def UpperCamelCase ( self : Tuple , snake_case__ : str , snake_case__ : Optional[str] = None ): """simple docstring""" _UpperCAmelCase = self._tokenizer.model.save(snake_case__ , name=snake_case__ ) return tuple(snake_case__ ) def UpperCamelCase ( self : Dict , snake_case__ : "Conversation" ): """simple docstring""" _UpperCAmelCase = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(snake_case__ , add_special_tokens=snake_case__ ) + [self.eos_token_id] ) if len(snake_case__ ) > self.model_max_length: _UpperCAmelCase = input_ids[-self.model_max_length :] return input_ids
133
0
"""simple docstring""" import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'vocab.txt', 'sentencepiece_model_ckpt': 'sentencepiece.bpe.model'} _A = { 'sentencepiece_model_file': 'sentencepiece.bpe.model', 'vocab_file': 'vocab.txt', } _A = { 'vocab_file': { 'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt', 'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt', }, 'sentencepiece_model_file': { 'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model', 'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model', }, } _A = { 'ernie-m-base': 5_1_4, 'ernie-m-large': 5_1_4, } _A = { 'ernie-m-base': {'do_lower_case': False}, 'ernie-m-large': {'do_lower_case': False}, } class _lowercase ( __UpperCAmelCase ): lowercase_ = ["input_ids"] lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = RESOURCE_FILES_NAMES def __init__( self , UpperCAmelCase_ , UpperCAmelCase_=None , UpperCAmelCase_=False , UpperCAmelCase_="utf8" , UpperCAmelCase_="[UNK]" , UpperCAmelCase_="[SEP]" , UpperCAmelCase_="[PAD]" , UpperCAmelCase_="[CLS]" , UpperCAmelCase_="[MASK]" , UpperCAmelCase_ = None , **UpperCAmelCase_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. lowerCamelCase : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , vocab_file=UpperCAmelCase_ , encoding=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) lowerCamelCase : int = do_lower_case lowerCamelCase : Union[str, Any] = sentencepiece_model_ckpt lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: lowerCamelCase : Tuple = self.load_vocab(filepath=UpperCAmelCase_ ) else: lowerCamelCase : Tuple = {self.sp_model.id_to_piece(UpperCAmelCase_ ): id for id in range(self.sp_model.get_piece_size() )} lowerCamelCase : Union[str, Any] = {v: k for k, v in self.vocab.items()} def _UpperCamelCase ( self , UpperCAmelCase_ ) -> int: if text is None: return None lowerCamelCase : Union[str, Any] = self.tokenize(UpperCAmelCase_ ) lowerCamelCase , lowerCamelCase : Tuple = '', [] for i, ch in enumerate(UpperCAmelCase_ ): if ch in self.SP_CHAR_MAPPING: lowerCamelCase : Dict = self.SP_CHAR_MAPPING.get(UpperCAmelCase_ ) else: lowerCamelCase : Tuple = unicodedata.normalize('NFKC' , UpperCAmelCase_ ) if self.is_whitespace(UpperCAmelCase_ ): continue normalized_text += ch char_mapping.extend([i] * len(UpperCAmelCase_ ) ) lowerCamelCase , lowerCamelCase , lowerCamelCase : int = normalized_text, [], 0 if self.do_lower_case: lowerCamelCase : Tuple = text.lower() for token in split_tokens: if token[:1] == "▁": lowerCamelCase : Tuple = token[1:] lowerCamelCase : str = text[offset:].index(UpperCAmelCase_ ) + offset lowerCamelCase : List[Any] = start + len(UpperCAmelCase_ ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) lowerCamelCase : List[Any] = end return token_mapping @property def _UpperCamelCase ( self ) -> Optional[int]: return len(self.vocab ) def _UpperCamelCase ( self ) -> List[Any]: return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self ) -> List[Any]: lowerCamelCase : Dict = self.__dict__.copy() lowerCamelCase : Optional[Any] = None return state def __setstate__( self , UpperCAmelCase_ ) -> List[str]: lowerCamelCase : Tuple = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): lowerCamelCase : Any = {} lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Optional[int]: return "".join((self.SP_CHAR_MAPPING.get(UpperCAmelCase_ , UpperCAmelCase_ ) for c in text) ) def _UpperCamelCase ( self , UpperCAmelCase_ , UpperCAmelCase_=False , UpperCAmelCase_=64 , UpperCAmelCase_=0.1 ) -> Union[str, Any]: if self.sp_model_kwargs.get('enable_sampling' ) is True: lowerCamelCase : Optional[int] = True if self.sp_model_kwargs.get('alpha' ) is not None: lowerCamelCase : str = self.sp_model_kwargs.get('alpha' ) if self.sp_model_kwargs.get('nbest_size' ) is not None: lowerCamelCase : Dict = self.sp_model_kwargs.get('nbest_size' ) if not enable_sampling: lowerCamelCase : str = self.sp_model.EncodeAsPieces(UpperCAmelCase_ ) else: lowerCamelCase : int = self.sp_model.SampleEncodeAsPieces(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) lowerCamelCase : Optional[int] = [] for pi, piece in enumerate(UpperCAmelCase_ ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(UpperCAmelCase_ ) and pi != 0: new_pieces.append(UpperCAmelCase_ ) continue else: continue lowerCamelCase : List[Any] = 0 for i, chunk in enumerate(UpperCAmelCase_ ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(UpperCAmelCase_ ) or self.is_punct(UpperCAmelCase_ ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(UpperCAmelCase_ ) lowerCamelCase : int = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) lowerCamelCase : int = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) lowerCamelCase : str = i if len(UpperCAmelCase_ ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def _UpperCamelCase ( self , UpperCAmelCase_ ) -> List[str]: lowerCamelCase : int = ''.join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , ' ' ).strip() return out_string def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Any: lowerCamelCase : Any = self.convert_ids_to_tokens(UpperCAmelCase_ ) lowerCamelCase : Optional[Any] = ''.join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , ' ' ).strip() return out_string def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Union[str, Any]: return self.vocab.get(UpperCAmelCase_ , self.vocab.get(self.unk_token ) ) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> int: return self.reverse_vocab.get(UpperCAmelCase_ , self.unk_token ) def _UpperCamelCase ( self , UpperCAmelCase_ , UpperCAmelCase_=None ) -> Optional[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase : List[str] = [self.cls_token_id] lowerCamelCase : List[Any] = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def _UpperCamelCase ( self , UpperCAmelCase_ , UpperCAmelCase_=None ) -> int: if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def _UpperCamelCase ( self , UpperCAmelCase_ , UpperCAmelCase_=None , UpperCAmelCase_=False ) -> List[str]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1, 1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def _UpperCamelCase ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ) -> List[int]: # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(UpperCAmelCase_ ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(UpperCAmelCase_ ) + 1) + [1] * (len(UpperCAmelCase_ ) + 3) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Optional[int]: if "\u4e00" <= char <= "\u9fff": return True return False def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Optional[int]: if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def _UpperCamelCase ( self , UpperCAmelCase_ ) -> int: if char in ",;:.?!~,;:。?!《》【】": return True return False def _UpperCamelCase ( self , UpperCAmelCase_ ) -> List[Any]: if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(UpperCAmelCase_ ) == 1: lowerCamelCase : Dict = unicodedata.category(UpperCAmelCase_ ) if cat == "Zs": return True return False def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Optional[Any]: lowerCamelCase : Optional[Any] = {} with io.open(UpperCAmelCase_ , 'r' , encoding='utf-8' ) as f: for index, line in enumerate(UpperCAmelCase_ ): lowerCamelCase : List[str] = line.rstrip('\n' ) lowerCamelCase : Any = int(UpperCAmelCase_ ) return token_to_idx def _UpperCamelCase ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ) -> Tuple[str]: lowerCamelCase : str = 0 if os.path.isdir(UpperCAmelCase_ ): lowerCamelCase : Optional[Any] = os.path.join( UpperCAmelCase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: lowerCamelCase : Tuple = (filename_prefix + '-' if filename_prefix else '') + save_directory with open(UpperCAmelCase_ , 'w' , encoding='utf-8' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda UpperCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ' Please check that the vocabulary is not corrupted!' ) lowerCamelCase : Optional[int] = token_index writer.write(token + '\n' ) index += 1 lowerCamelCase : Dict = os.path.join(UpperCAmelCase_ , 'sentencepiece.bpe.model' ) with open(UpperCAmelCase_ , 'wb' ) as fi: lowerCamelCase : int = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (vocab_file,)
205
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _A = logging.get_logger('transformers.models.speecht5') def UpperCAmelCase ( a_, a_, a_ ): '''simple docstring''' hf_model.apply_weight_norm() lowerCamelCase : str = checkpoint['input_conv.weight_g'] lowerCamelCase : int = checkpoint['input_conv.weight_v'] lowerCamelCase : Optional[Any] = checkpoint['input_conv.bias'] for i in range(len(config.upsample_rates ) ): lowerCamelCase : Tuple = checkpoint[F"""upsamples.{i}.1.weight_g"""] lowerCamelCase : Any = checkpoint[F"""upsamples.{i}.1.weight_v"""] lowerCamelCase : List[str] = checkpoint[F"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): lowerCamelCase : Optional[Any] = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_g"""] lowerCamelCase : Tuple = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_v"""] lowerCamelCase : Union[str, Any] = checkpoint[F"""blocks.{i}.convs1.{j}.1.bias"""] lowerCamelCase : Dict = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_g"""] lowerCamelCase : str = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_v"""] lowerCamelCase : Optional[Any] = checkpoint[F"""blocks.{i}.convs2.{j}.1.bias"""] lowerCamelCase : Any = checkpoint['output_conv.1.weight_g'] lowerCamelCase : Tuple = checkpoint['output_conv.1.weight_v'] lowerCamelCase : int = checkpoint['output_conv.1.bias'] hf_model.remove_weight_norm() @torch.no_grad() def UpperCAmelCase ( a_, a_, a_, a_=None, a_=None, ): '''simple docstring''' if config_path is not None: lowerCamelCase : str = SpeechTaHifiGanConfig.from_pretrained(a_ ) else: lowerCamelCase : Dict = SpeechTaHifiGanConfig() lowerCamelCase : int = SpeechTaHifiGan(a_ ) lowerCamelCase : Optional[Any] = torch.load(a_ ) load_weights(orig_checkpoint['model']['generator'], a_, a_ ) lowerCamelCase : Tuple = np.load(a_ ) lowerCamelCase : str = stats[0].reshape(-1 ) lowerCamelCase : Optional[int] = stats[1].reshape(-1 ) lowerCamelCase : Dict = torch.from_numpy(a_ ).float() lowerCamelCase : Optional[int] = torch.from_numpy(a_ ).float() model.save_pretrained(a_ ) if repo_id: print('Pushing to the hub...' ) model.push_to_hub(a_ ) if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) _A = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
205
1
import math def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if not isinstance(snake_case__ , snake_case__ ): __a = f"Input value of [number={number}] must be an integer" raise TypeError(snake_case__ ) if number < 1: __a = f"Input value of [number={number}] must be > 0" raise ValueError(snake_case__ ) elif number == 1: return 3 elif number == 2: return 5 else: __a = int(math.log(number // 3 , 2 ) ) + 2 __a = [3, 5] __a = 2 __a = 3 for block in range(1 , snake_case__ ): for _ in range(snake_case__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): lowerCamelCase__ = 0 try: lowerCamelCase__ = proth(number) except ValueError: print(F"""ValueError: there is no {number}th Proth number""") continue print(F"""The {number}th Proth number: {value}""")
302
import argparse import os import re _snake_case = '''src/transformers/models/auto''' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict _snake_case = re.compile(r'''[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict''') # re pattern that matches identifiers in mappings _snake_case = re.compile(r'''\s*\(\s*"(\S[^"]+)"''') def _UpperCamelCase ( snake_case__, snake_case__ = False ) -> List[Any]: with open(snake_case__, "r", encoding="utf-8" ) as f: __UpperCAmelCase : Dict = f.read() __UpperCAmelCase : Optional[Any] = content.split("\n" ) __UpperCAmelCase : int = [] __UpperCAmelCase : Optional[int] = 0 while line_idx < len(snake_case__ ): if _re_intro_mapping.search(lines[line_idx] ) is not None: __UpperCAmelCase : 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 __UpperCAmelCase : Dict = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": __UpperCAmelCase : str = 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 __UpperCAmelCase : Dict = sorted(snake_case__, key=lambda snake_case__ : _re_identifier.search(snake_case__ ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(snake_case__, "w", encoding="utf-8" ) as f: f.write("\n".join(snake_case__ ) ) elif "\n".join(snake_case__ ) != content: return True def _UpperCamelCase ( snake_case__ = False ) -> Any: __UpperCAmelCase : str = [os.path.join(snake_case__, snake_case__ ) for f in os.listdir(snake_case__ ) if f.endswith(".py" )] __UpperCAmelCase : Optional[Any] = [sort_auto_mapping(snake_case__, overwrite=snake_case__ ) for fname in fnames] if not overwrite and any(snake_case__ ): __UpperCAmelCase : List[Any] = [f for f, d in zip(snake_case__, snake_case__ ) if d] raise ValueError( f'''The following files have auto mappings that need sorting: {', '.join(snake_case__ )}. Run `make style` to fix''' " this." ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') _snake_case = parser.parse_args() sort_all_auto_mappings(not args.check_only)
157
0
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class _lowercase : def __init__( self : List[Any] , snake_case : int , snake_case : Any=9_9 , snake_case : Tuple=1_3 , snake_case : str=7 , snake_case : List[str]=9 , snake_case : Optional[Any]=True , snake_case : Any=True , snake_case : Optional[Any]=False , snake_case : List[str]=3_2 , snake_case : str=5 , snake_case : Any=4 , snake_case : List[str]=3_7 , snake_case : Optional[Any]=8 , snake_case : Optional[Any]=0.1 , snake_case : Dict=0.002 , snake_case : Any=1 , snake_case : Optional[int]=0 , snake_case : List[str]=0 , snake_case : List[str]=None , snake_case : List[str]=None , ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : int = parent UpperCamelCase_ : List[Any] = batch_size UpperCamelCase_ : int = encoder_seq_length UpperCamelCase_ : int = decoder_seq_length # For common tests UpperCamelCase_ : List[Any] = self.decoder_seq_length UpperCamelCase_ : Optional[Any] = is_training UpperCamelCase_ : Tuple = use_attention_mask UpperCamelCase_ : int = use_labels UpperCamelCase_ : List[str] = vocab_size UpperCamelCase_ : Dict = hidden_size UpperCamelCase_ : Any = num_hidden_layers UpperCamelCase_ : Any = num_attention_heads UpperCamelCase_ : Dict = d_ff UpperCamelCase_ : List[Any] = relative_attention_num_buckets UpperCamelCase_ : List[Any] = dropout_rate UpperCamelCase_ : Dict = initializer_factor UpperCamelCase_ : Union[str, Any] = eos_token_id UpperCamelCase_ : Optional[int] = pad_token_id UpperCamelCase_ : List[str] = decoder_start_token_id UpperCamelCase_ : str = None UpperCamelCase_ : int = decoder_layers def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> List[str]: """simple docstring""" return TaConfig.from_pretrained('google/umt5-base' ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : Optional[int] , snake_case : Any , snake_case : Optional[int] , snake_case : Optional[int]=None , snake_case : List[Any]=None , snake_case : int=None , snake_case : Optional[int]=None , snake_case : Tuple=None , ) -> List[str]: """simple docstring""" if attention_mask is None: UpperCamelCase_ : Optional[Any] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: UpperCamelCase_ : Optional[int] = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: UpperCamelCase_ : Optional[int] = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=snake_case ) if decoder_head_mask is None: UpperCamelCase_ : Dict = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=snake_case ) if cross_attn_head_mask is None: UpperCamelCase_ : Optional[Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=snake_case ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) UpperCamelCase_ : Any = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input UpperCamelCase_ : Union[str, Any] = input_ids.clamp(self.pad_token_id + 1 ) UpperCamelCase_ : Any = decoder_input_ids.clamp(self.pad_token_id + 1 ) UpperCamelCase_ : Dict = self.get_config() UpperCamelCase_ : Dict = config.num_attention_heads UpperCamelCase_ : Optional[int] = self.prepare_inputs_dict(snake_case , snake_case , snake_case ) return config, input_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_, UpperCamelCase_ : Any = self.prepare_config_and_inputs() return config, inputs_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Dict: """simple docstring""" return TaConfig( vocab_size=1_6_6 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[int]: """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : Dict , snake_case : List[str] , snake_case : Tuple , snake_case : int , snake_case : List[str] , snake_case : Optional[Any] , ) -> Tuple: """simple docstring""" UpperCamelCase_ : int = UMTaModel(config=snake_case ) model.to(snake_case ) model.eval() UpperCamelCase_ : Any = model( input_ids=snake_case , decoder_input_ids=snake_case , attention_mask=snake_case , decoder_attention_mask=snake_case , ) UpperCamelCase_ : List[str] = model(input_ids=snake_case , decoder_input_ids=snake_case ) UpperCamelCase_ : Optional[Any] = result.last_hidden_state UpperCamelCase_ : Optional[Any] = result.past_key_values UpperCamelCase_ : Optional[int] = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(snake_case ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : Tuple , snake_case : List[Any] , snake_case : Optional[int] , snake_case : Any , snake_case : Tuple , snake_case : str , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : int = UMTaModel(config=snake_case ).get_decoder().to(snake_case ).eval() # first forward pass UpperCamelCase_ : str = model(snake_case , use_cache=snake_case ) UpperCamelCase_ : List[Any] = model(snake_case ) UpperCamelCase_ : Dict = model(snake_case , use_cache=snake_case ) self.parent.assertTrue(len(snake_case ) == len(snake_case ) ) self.parent.assertTrue(len(snake_case ) == len(snake_case ) + 1 ) UpperCamelCase_, UpperCamelCase_ : Optional[Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase_ : Any = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and UpperCamelCase_ : List[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase_ : List[Any] = model(snake_case )['last_hidden_state'] UpperCamelCase_ : List[str] = model(snake_case , past_key_values=snake_case )['last_hidden_state'] # select random slice UpperCamelCase_ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase_ : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase_ : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : Tuple , snake_case : int , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : Optional[int] = UMTaModel(config=snake_case ).to(snake_case ).half().eval() UpperCamelCase_ : Union[str, Any] = model(**snake_case )['last_hidden_state'] self.parent.assertFalse(torch.isnan(snake_case ).any().item() ) @require_torch class _lowercase ( snake_case_ , snake_case_ , snake_case_ , unittest.TestCase ): lowercase = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) lowercase = (UMTaForConditionalGeneration,) if is_torch_available() else () lowercase = ( { 'conversational': UMTaForConditionalGeneration, 'feature-extraction': UMTaModel, 'summarization': UMTaForConditionalGeneration, 'text2text-generation': UMTaForConditionalGeneration, 'translation': UMTaForConditionalGeneration, 'question-answering': UMTaForQuestionAnswering, } if is_torch_available() else {} ) lowercase = True lowercase = False lowercase = False lowercase = True lowercase = True # The small UMT5 model needs higher percentages for CPU/MP tests lowercase = [0.8, 0.9] def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> List[Any]: """simple docstring""" UpperCamelCase_ : Optional[Any] = UMTaModelTester(self ) @unittest.skip('Test has a segmentation fault on torch 1.8.0' ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> List[str]: """simple docstring""" UpperCamelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() UpperCamelCase_ : List[str] = UMTaModel(config_and_inputs[0] ).to(snake_case ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( snake_case , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f"{tmpdirname}/t5_test.onnx" , export_params=snake_case , opset_version=9 , input_names=['input_ids', 'decoder_input_ids'] , ) @unittest.skipIf(torch_device == 'cpu' , 'Cant do half precision' ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*snake_case ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : Tuple = ['encoder_attentions', 'decoder_attentions', 'cross_attentions'] UpperCamelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() UpperCamelCase_ : Union[str, Any] = config_and_inputs[0] UpperCamelCase_ : Tuple = UMTaForConditionalGeneration(snake_case ).eval() model.to(snake_case ) UpperCamelCase_ : str = { 'head_mask': torch.zeros(config.num_layers , config.num_heads , device=snake_case ), 'decoder_head_mask': torch.zeros(config.num_decoder_layers , config.num_heads , device=snake_case ), 'cross_attn_head_mask': torch.zeros(config.num_decoder_layers , config.num_heads , device=snake_case ), } for attn_name, (name, mask) in zip(snake_case , head_masking.items() ): UpperCamelCase_ : Optional[int] = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": UpperCamelCase_ : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_heads , device=snake_case ) UpperCamelCase_ : Any = model.generate( config_and_inputs[1]['input_ids'] , num_beams=1 , max_length=3 , output_attentions=snake_case , return_dict_in_generate=snake_case , **snake_case , ) # We check the state of decoder_attentions and cross_attentions just from the last step UpperCamelCase_ : int = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('Does not work on the tiny model as we keep hitting edge cases.' ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class _lowercase ( unittest.TestCase ): @slow @unittest.skip( 'Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged' ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> List[Any]: """simple docstring""" UpperCamelCase_ : str = UMTaForConditionalGeneration.from_pretrained('google/umt5-small' , return_dict=snake_case ).to(snake_case ) UpperCamelCase_ : int = AutoTokenizer.from_pretrained('google/umt5-small' , use_fast=snake_case , legacy=snake_case ) UpperCamelCase_ : Dict = [ 'Bonjour monsieur <extra_id_0> bien <extra_id_1>.', 'No se como puedo <extra_id_0>.', 'This is the reason why we <extra_id_0> them.', 'The <extra_id_0> walks in <extra_id_1>, seats', 'A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.', ] UpperCamelCase_ : Dict = tokenizer(snake_case , return_tensors='pt' , padding=snake_case ).input_ids # fmt: off UpperCamelCase_ : List[str] = torch.tensor( [ [ 3_8_5_3_0, 2_1_0_7_0_3, 2_5_6_2_9_9, 1_4_1_0, 2_5_6_2_9_8, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_2_6, 3_2_1, 6_7_1, 2_5_9_2_2, 2_5_6_2_9_9, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_4_6_0, 3_3_9, 3_1_2, 1_9_0_1_4, 1_0_6_2_0, 7_5_8, 2_5_6_2_9_9, 2_3_5_5,2_7_4, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_1_7, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 3_0_1, 2_5_6_2_9_8, 2_7_5, 1_1_9_9_8_3,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_2_0, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 2_2_3_4, 2_8_9, 2_2_7_5, 3_3_3,6_1_3_9_1, 2_8_9, 2_5_6_2_9_8, 5_4_3, 2_5_6_2_9_7, 1_6_8_7_1_4, 3_2_9, 2_5_6_2_9_6,2_7_4, 1], ] ) # fmt: on torch.testing.assert_allclose(snake_case , snake_case ) UpperCamelCase_ : int = model.generate(input_ids.to(snake_case ) ) UpperCamelCase_ : List[Any] = [ '<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>', '<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', ] UpperCamelCase_ : Dict = tokenizer.batch_decode(snake_case ) self.assertEqual(snake_case , snake_case )
50
import math import flax.linen as nn import jax.numpy as jnp def __lowercase ( lowerCamelCase : jnp.ndarray , lowerCamelCase : int , lowerCamelCase : float = 1 , lowerCamelCase : float = 1 , lowerCamelCase : float = 1.0e4 , lowerCamelCase : bool = False , lowerCamelCase : float = 1.0 , ): assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"Embedding dimension {embedding_dim} should be even" UpperCamelCase_ : Dict = float(embedding_dim // 2 ) UpperCamelCase_ : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) UpperCamelCase_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(lowerCamelCase , dtype=jnp.floataa ) * -log_timescale_increment ) UpperCamelCase_ : int = jnp.expand_dims(lowerCamelCase , 1 ) * jnp.expand_dims(lowerCamelCase , 0 ) # scale embeddings UpperCamelCase_ : Tuple = scale * emb if flip_sin_to_cos: UpperCamelCase_ : Tuple = jnp.concatenate([jnp.cos(lowerCamelCase ), jnp.sin(lowerCamelCase )] , axis=1 ) else: UpperCamelCase_ : Optional[int] = jnp.concatenate([jnp.sin(lowerCamelCase ), jnp.cos(lowerCamelCase )] , axis=1 ) UpperCamelCase_ : Optional[Any] = jnp.reshape(lowerCamelCase , [jnp.shape(lowerCamelCase )[0], embedding_dim] ) return signal class _lowercase ( nn.Module ): lowercase = 3_2 lowercase = jnp.floataa @nn.compact def __call__( self : str , snake_case : Union[str, Any] ) -> Dict: """simple docstring""" UpperCamelCase_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(snake_case ) UpperCamelCase_ : int = nn.silu(snake_case ) UpperCamelCase_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(snake_case ) return temb class _lowercase ( nn.Module ): lowercase = 3_2 lowercase = False lowercase = 1 @nn.compact def __call__( self : int , snake_case : Any ) -> str: """simple docstring""" return get_sinusoidal_embeddings( snake_case , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
50
1
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. __UpperCAmelCase = 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 lowercase__ ( __snake_case : List[Any] ): '''simple docstring''' from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_lowerCamelCase ) def lowercase__ ( __snake_case : Union[str, Any] ): '''simple docstring''' from diffusers.utils.testing_utils import pytest_terminal_summary_main UpperCAmelCase_ : Union[str, Any] = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(_lowerCamelCase , id=_lowerCamelCase )
29
'''simple docstring''' import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor UpperCamelCase_ = logging.get_logger(__name__) class a_ (_a ): def __init__( self , *snake_case_ , **snake_case_ ): warnings.warn( """The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DonutImageProcessor instead.""" , snake_case_ , ) super().__init__(*snake_case_ , **snake_case_ )
309
0
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase ) -> list[int]: # This function is recursive SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else SCREAMING_SNAKE_CASE__ : List[Any] = array[0] SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : list[int] = [] while not is_found and i < array_length: if array[i] < pivot: SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : str = [element for element in array[i:] if element >= array[i]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = longest_subsequence(__lowerCAmelCase ) if len(__lowerCAmelCase ) > len(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = temp_array else: i += 1 SCREAMING_SNAKE_CASE__ : Any = [element for element in array[1:] if element >= pivot] SCREAMING_SNAKE_CASE__ : str = [pivot, *longest_subsequence(__lowerCAmelCase )] if len(__lowerCAmelCase ) > len(__lowerCAmelCase ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
354
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=False , _a=True , _a="None" , _a=3 , _a=4 , _a=None , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : str = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_input_mask SCREAMING_SNAKE_CASE__ : str = use_token_type_ids SCREAMING_SNAKE_CASE__ : Tuple = use_labels SCREAMING_SNAKE_CASE__ : List[str] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = num_labels SCREAMING_SNAKE_CASE__ : Optional[int] = num_choices SCREAMING_SNAKE_CASE__ : List[str] = relative_attention SCREAMING_SNAKE_CASE__ : str = position_biased_input SCREAMING_SNAKE_CASE__ : List[str] = pos_att_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = scope def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> Tuple: """simple docstring""" return DebertaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() SCREAMING_SNAKE_CASE__ : Any = 300 return config def _a ( self , _a ) -> List[str]: """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DebertaModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(_a , attention_mask=_a , token_type_ids=_a )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , token_type_ids=_a )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = DebertaForMaskedLM(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = DebertaForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(_a ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = DebertaForTokenClassification(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = DebertaForQuestionAnswering(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model( _a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) 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 _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 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__ ) , ) : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :str = ( { """feature-extraction""": DebertaModel, """fill-mask""": DebertaForMaskedLM, """question-answering""": DebertaForQuestionAnswering, """text-classification""": DebertaForSequenceClassification, """token-classification""": DebertaForTokenClassification, """zero-shot""": DebertaForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Union[str, Any] = True _SCREAMING_SNAKE_CASE :str = False _SCREAMING_SNAKE_CASE :Dict = False _SCREAMING_SNAKE_CASE :Dict = False _SCREAMING_SNAKE_CASE :Union[str, Any] = False def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = DebertaModelTester(self ) SCREAMING_SNAKE_CASE__ : str = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*_a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*_a ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Dict = DebertaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_torch @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @unittest.skip(reason="""Model not available yet""" ) def _a ( self ) -> Any: """simple docstring""" pass @slow def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DebertaModel.from_pretrained("""microsoft/deberta-base""" ) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a , attention_mask=_a )[0] # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _a , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
56
0
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 __A ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self ): """simple docstring""" for model_name in ["bert-base-uncased"]: __UpperCamelCase : List[str] =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : str =TFAutoModel.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : List[Any] =AutoModel.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in ["bert-base-uncased"]: __UpperCamelCase : Any =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : List[str] =TFAutoModelForPreTraining.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : Optional[Any] =AutoModelForPreTraining.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Tuple =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : str =TFAutoModelForCausalLM.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) __UpperCamelCase , __UpperCamelCase : Tuple =TFAutoModelForCausalLM.from_pretrained( lowerCamelCase__ , output_loading_info=lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : Optional[int] =AutoModelForCausalLM.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) __UpperCamelCase , __UpperCamelCase : Union[str, Any] =AutoModelForCausalLM.from_pretrained( lowerCamelCase__ , output_loading_info=lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : int =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : Dict =TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : List[Any] =AutoModelWithLMHead.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : List[Any] =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : List[str] =TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) __UpperCamelCase , __UpperCamelCase : Tuple =TFAutoModelForMaskedLM.from_pretrained( lowerCamelCase__ , output_loading_info=lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : List[str] =AutoModelForMaskedLM.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) __UpperCamelCase , __UpperCamelCase : Optional[Any] =AutoModelForMaskedLM.from_pretrained( lowerCamelCase__ , output_loading_info=lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Any =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : List[Any] =TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) __UpperCamelCase , __UpperCamelCase : List[str] =TFAutoModelForSeqaSeqLM.from_pretrained( lowerCamelCase__ , output_loading_info=lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : Dict =AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) __UpperCamelCase , __UpperCamelCase : List[Any] =AutoModelForSeqaSeqLM.from_pretrained( lowerCamelCase__ , output_loading_info=lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in ["bert-base-uncased"]: __UpperCamelCase : str =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =TFAutoModelForSequenceClassification.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : str =AutoModelForSequenceClassification.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in ["bert-base-uncased"]: __UpperCamelCase : List[Any] =AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : Tuple =TFAutoModelForQuestionAnswering.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) __UpperCamelCase : Optional[Any] =AutoModelForQuestionAnswering.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : int =TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) , 14410 ) __UpperCamelCase : str =AutoModelWithLMHead.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) , 14410 ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Union[str, Any] =TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ , from_pt=lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) , 14410 ) __UpperCamelCase : int =AutoModelWithLMHead.from_pretrained(lowerCamelCase__ , from_tf=lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ , lowerCamelCase__ ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) , 14410 )
71
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class __A : """simple docstring""" UpperCamelCase__ : int =XGLMConfig UpperCamelCase__ : Optional[Any] ={} UpperCamelCase__ : List[str] ="""gelu""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=14 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=99 , lowerCamelCase__=32 , lowerCamelCase__=2 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=0.02 , ): """simple docstring""" __UpperCamelCase : Tuple =parent __UpperCamelCase : List[str] =batch_size __UpperCamelCase : str =seq_length __UpperCamelCase : Dict =is_training __UpperCamelCase : Tuple =use_input_mask __UpperCamelCase : List[Any] =use_labels __UpperCamelCase : Any =vocab_size __UpperCamelCase : List[Any] =d_model __UpperCamelCase : Optional[int] =num_hidden_layers __UpperCamelCase : List[str] =num_attention_heads __UpperCamelCase : Optional[int] =ffn_dim __UpperCamelCase : str =activation_function __UpperCamelCase : Any =activation_dropout __UpperCamelCase : Optional[int] =attention_dropout __UpperCamelCase : Optional[int] =max_position_embeddings __UpperCamelCase : Any =initializer_range __UpperCamelCase : Dict =None __UpperCamelCase : Optional[int] =0 __UpperCamelCase : Optional[Any] =2 __UpperCamelCase : str =1 def __lowercase ( self ): """simple docstring""" return XGLMConfig.from_pretrained('facebook/xglm-564M' ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[Any] =tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) __UpperCamelCase : Union[str, Any] =None if self.use_input_mask: __UpperCamelCase : Dict =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase : Any =self.get_config() __UpperCamelCase : Optional[Any] =floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def __lowercase ( self ): """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=lowerCamelCase__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=lowerCamelCase__ , ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) : int =config_and_inputs __UpperCamelCase : Optional[Any] ={ 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class __A ( a , a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : Union[str, Any] =(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () UpperCamelCase__ : str =(TFXGLMForCausalLM,) if is_tf_available() else () UpperCamelCase__ : Optional[Any] =( {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {} ) UpperCamelCase__ : Tuple =False UpperCamelCase__ : Tuple =False UpperCamelCase__ : Optional[Any] =False def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =TFXGLMModelTester(self ) __UpperCamelCase : Dict =ConfigTester(self , config_class=lowerCamelCase__ , n_embd=37 ) def __lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() @slow def __lowercase ( self ): """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Optional[Any] =TFXGLMModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' ) def __lowercase ( self ): """simple docstring""" super().test_resize_token_embeddings() @require_tf class __A ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self , lowerCamelCase__=True ): """simple docstring""" __UpperCamelCase : int =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : List[str] =tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __UpperCamelCase : str =[2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581] # fmt: on __UpperCamelCase : Optional[Any] =model.generate(lowerCamelCase__ , do_sample=lowerCamelCase__ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Union[str, Any] =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) tf.random.set_seed(0 ) __UpperCamelCase : str =tokenizer('Today is a nice day and' , return_tensors='tf' ) __UpperCamelCase : Union[str, Any] =tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0' ): __UpperCamelCase : Any =model.generate(lowerCamelCase__ , do_sample=lowerCamelCase__ , seed=[7, 0] ) __UpperCamelCase : Tuple =tokenizer.decode(output_ids[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : List[Any] =( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Optional[Any] =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Optional[Any] ='left' # use different length sentences to test batching __UpperCamelCase : Optional[int] =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __UpperCamelCase : List[Any] =tokenizer(lowerCamelCase__ , return_tensors='tf' , padding=lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =inputs['input_ids'] __UpperCamelCase : Dict =model.generate(input_ids=lowerCamelCase__ , attention_mask=inputs['attention_mask'] , max_new_tokens=12 ) __UpperCamelCase : List[Any] =tokenizer(sentences[0] , return_tensors='tf' ).input_ids __UpperCamelCase : Dict =model.generate(input_ids=lowerCamelCase__ , max_new_tokens=12 ) __UpperCamelCase : Any =tokenizer(sentences[1] , return_tensors='tf' ).input_ids __UpperCamelCase : Optional[Any] =model.generate(input_ids=lowerCamelCase__ , max_new_tokens=12 ) __UpperCamelCase : Optional[int] =tokenizer.batch_decode(lowerCamelCase__ , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : int =tokenizer.decode(output_padded[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : Any =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , [non_padded_sentence, padded_sentence] )
71
1
'''simple docstring''' import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename __a = "http://www.mocksite.com/file1.txt" __a = "\"text\": [\"foo\", \"foo\"]" __a = "6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8" class UpperCAmelCase_ : """simple docstring""" lowercase = 2_00 lowercase = {"Content-Length": "100"} lowercase = {} def lowerCamelCase ( self : Union[str, Any] , **snake_case_ : Union[str, Any] ): return [bytes(snake_case_ , """utf-8""" )] def __snake_case( *_lowerCAmelCase , **_lowerCAmelCase ) -> str: return MockResponse() @pytest.mark.parametrize("""urls_type""" , [str, list, dict] ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: import requests monkeypatch.setattr(_lowerCAmelCase , """request""" , _lowerCAmelCase ) snake_case__ : List[str] = URL if issubclass(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : Any = url elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : str = [url] elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : Optional[int] = {"""train""": url} snake_case__ : str = """dummy""" snake_case__ : Dict = """downloads""" snake_case__ : Optional[int] = tmp_path snake_case__ : Union[str, Any] = DownloadConfig( cache_dir=os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , use_etag=_lowerCAmelCase , ) snake_case__ : Tuple = DownloadManager(dataset_name=_lowerCAmelCase , download_config=_lowerCAmelCase ) snake_case__ : Union[str, Any] = dl_manager.download(_lowerCAmelCase ) snake_case__ : Any = urls for downloaded_paths in [downloaded_paths]: if isinstance(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : str = [downloaded_paths] snake_case__ : List[str] = [urls] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): assert "train" in downloaded_paths.keys() snake_case__ : int = downloaded_paths.values() snake_case__ : List[Any] = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(_lowerCAmelCase , _lowerCAmelCase ): assert downloaded_path == dl_manager.downloaded_paths[input_url] snake_case__ : Tuple = Path(_lowerCAmelCase ) snake_case__ : int = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() snake_case__ : Optional[int] = downloaded_path.read_text() assert content == CONTENT snake_case__ : Union[str, Any] = downloaded_path.with_suffix(""".json""" ) assert metadata_downloaded_path.exists() snake_case__ : int = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize("""paths_type""" , [str, list, dict] ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: snake_case__ : int = str(_lowerCAmelCase ) if issubclass(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : List[str] = filename elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : List[str] = [filename] elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : Any = {"""train""": filename} snake_case__ : int = """dummy""" snake_case__ : Optional[Any] = xz_file.parent snake_case__ : str = """extracted""" snake_case__ : Tuple = DownloadConfig( cache_dir=_lowerCAmelCase , use_etag=_lowerCAmelCase , ) snake_case__ : Tuple = DownloadManager(dataset_name=_lowerCAmelCase , download_config=_lowerCAmelCase ) snake_case__ : List[str] = dl_manager.extract(_lowerCAmelCase ) snake_case__ : List[str] = paths for extracted_paths in [extracted_paths]: if isinstance(_lowerCAmelCase , _lowerCAmelCase ): snake_case__ : int = [extracted_paths] snake_case__ : List[str] = [paths] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): assert "train" in extracted_paths.keys() snake_case__ : Tuple = extracted_paths.values() snake_case__ : Dict = paths.values() assert extracted_paths for extracted_path, input_path in zip(_lowerCAmelCase , _lowerCAmelCase ): assert extracted_path == dl_manager.extracted_paths[input_path] snake_case__ : Optional[Any] = Path(_lowerCAmelCase ) snake_case__ : Optional[int] = extracted_path.parts assert parts[-1] == hash_url_to_filename(_lowerCAmelCase , etag=_lowerCAmelCase ) assert parts[-2] == extracted_subdir assert extracted_path.exists() snake_case__ : int = extracted_path.read_text() snake_case__ : int = text_file.read_text() assert extracted_file_content == expected_file_content def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert path.endswith(""".jsonl""" ) for num_items, line in enumerate(_lowerCAmelCase , start=1 ): snake_case__ : List[Any] = json.loads(line.decode("""utf-8""" ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize("""archive_jsonl""" , ["""tar_jsonl_path""", """zip_jsonl_path"""] ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> int: snake_case__ : Union[str, Any] = request.getfixturevalue(_lowerCAmelCase ) snake_case__ : Optional[Any] = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(_lowerCAmelCase ) , start=1 ): _test_jsonl(_lowerCAmelCase , _lowerCAmelCase ) assert num_jsonl == 2 @pytest.mark.parametrize("""archive_nested_jsonl""" , ["""tar_nested_jsonl_path""", """zip_nested_jsonl_path"""] ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> Dict: snake_case__ : List[Any] = request.getfixturevalue(_lowerCAmelCase ) snake_case__ : Union[str, Any] = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(_lowerCAmelCase ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(_lowerCAmelCase ) , start=1 ): _test_jsonl(_lowerCAmelCase , _lowerCAmelCase ) assert num_tar == 1 assert num_jsonl == 2 def __snake_case( _lowerCAmelCase ) -> List[str]: snake_case__ : List[str] = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(_lowerCAmelCase ) , start=1 ): assert os.path.basename(_lowerCAmelCase ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
360
'''simple docstring''' import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL __a = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False , ) -> List[Any]: output_path.parent.mkdir(parents=_lowerCAmelCase , exist_ok=_lowerCAmelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( _lowerCAmelCase , _lowerCAmelCase , f=output_path.as_posix() , input_names=_lowerCAmelCase , output_names=_lowerCAmelCase , dynamic_axes=_lowerCAmelCase , do_constant_folding=_lowerCAmelCase , use_external_data_format=_lowerCAmelCase , enable_onnx_checker=_lowerCAmelCase , opset_version=_lowerCAmelCase , ) else: export( _lowerCAmelCase , _lowerCAmelCase , f=output_path.as_posix() , input_names=_lowerCAmelCase , output_names=_lowerCAmelCase , dynamic_axes=_lowerCAmelCase , do_constant_folding=_lowerCAmelCase , opset_version=_lowerCAmelCase , ) @torch.no_grad() def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = False ) -> int: snake_case__ : str = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): snake_case__ : List[Any] = """cuda""" elif fpaa and not torch.cuda.is_available(): raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" ) else: snake_case__ : Tuple = """cpu""" snake_case__ : int = Path(_lowerCAmelCase ) # VAE DECODER snake_case__ : List[str] = AutoencoderKL.from_pretrained(model_path + """/vae""" ) snake_case__ : List[str] = vae_decoder.config.latent_channels # forward only through the decoder part snake_case__ : Dict = vae_decoder.decode onnx_export( _lowerCAmelCase , model_args=( torch.randn(1 , _lowerCAmelCase , 25 , 25 ).to(device=_lowerCAmelCase , dtype=_lowerCAmelCase ), False, ) , output_path=output_path / """vae_decoder""" / """model.onnx""" , ordered_input_names=["""latent_sample""", """return_dict"""] , output_names=["""sample"""] , dynamic_axes={ """latent_sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, } , opset=_lowerCAmelCase , ) del vae_decoder if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument( "--model_path", type=str, required=True, help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).", ) parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.") parser.add_argument( "--opset", default=14, type=int, help="The version of the ONNX operator set to use.", ) parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode") __a = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print("SD: Done: ONNX")
43
0
import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline __A =version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False , ): output_path.parent.mkdir(parents=_a , exist_ok=_a ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( _a , _a , f=output_path.as_posix() , input_names=_a , output_names=_a , dynamic_axes=_a , do_constant_folding=_a , use_external_data_format=_a , enable_onnx_checker=_a , opset_version=_a , ) else: export( _a , _a , f=output_path.as_posix() , input_names=_a , output_names=_a , dynamic_axes=_a , do_constant_folding=_a , opset_version=_a , ) @torch.no_grad() def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = False ): lowerCamelCase_ = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): lowerCamelCase_ = "cuda" elif fpaa and not torch.cuda.is_available(): raise ValueError("`float16` model export is only supported on GPUs with CUDA" ) else: lowerCamelCase_ = "cpu" lowerCamelCase_ = StableDiffusionPipeline.from_pretrained(_a , torch_dtype=_a ).to(_a ) lowerCamelCase_ = Path(_a ) # TEXT ENCODER lowerCamelCase_ = pipeline.text_encoder.config.max_position_embeddings lowerCamelCase_ = pipeline.text_encoder.config.hidden_size lowerCamelCase_ = pipeline.tokenizer( "A sample prompt" , padding="max_length" , max_length=pipeline.tokenizer.model_max_length , truncation=_a , return_tensors="pt" , ) onnx_export( pipeline.text_encoder , model_args=(text_input.input_ids.to(device=_a , dtype=torch.intaa )) , output_path=output_path / "text_encoder" / "model.onnx" , ordered_input_names=["input_ids"] , output_names=["last_hidden_state", "pooler_output"] , dynamic_axes={ "input_ids": {0: "batch", 1: "sequence"}, } , opset=_a , ) del pipeline.text_encoder # UNET lowerCamelCase_ = pipeline.unet.config.in_channels lowerCamelCase_ = pipeline.unet.config.sample_size lowerCamelCase_ = output_path / "unet" / "model.onnx" onnx_export( pipeline.unet , model_args=( torch.randn(2 , _a , _a , _a ).to(device=_a , dtype=_a ), torch.randn(2 ).to(device=_a , dtype=_a ), torch.randn(2 , _a , _a ).to(device=_a , dtype=_a ), False, ) , output_path=_a , ordered_input_names=["sample", "timestep", "encoder_hidden_states", "return_dict"] , output_names=["out_sample"] , dynamic_axes={ "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, "timestep": {0: "batch"}, "encoder_hidden_states": {0: "batch", 1: "sequence"}, } , opset=_a , use_external_data_format=_a , ) lowerCamelCase_ = str(unet_path.absolute().as_posix() ) lowerCamelCase_ = os.path.dirname(_a ) lowerCamelCase_ = onnx.load(_a ) # clean up existing tensor files shutil.rmtree(_a ) os.mkdir(_a ) # collate external tensor files into one onnx.save_model( _a , _a , save_as_external_data=_a , all_tensors_to_one_file=_a , location="weights.pb" , convert_attribute=_a , ) del pipeline.unet # VAE ENCODER lowerCamelCase_ = pipeline.vae lowerCamelCase_ = vae_encoder.config.in_channels lowerCamelCase_ = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder lowerCamelCase_ = lambda lowerCamelCase__ , lowerCamelCase__ : vae_encoder.encode(_a , _a )[0].sample() onnx_export( _a , model_args=( torch.randn(1 , _a , _a , _a ).to(device=_a , dtype=_a ), False, ) , output_path=output_path / "vae_encoder" / "model.onnx" , ordered_input_names=["sample", "return_dict"] , output_names=["latent_sample"] , dynamic_axes={ "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, } , opset=_a , ) # VAE DECODER lowerCamelCase_ = pipeline.vae lowerCamelCase_ = vae_decoder.config.latent_channels lowerCamelCase_ = vae_decoder.config.out_channels # forward only through the decoder part lowerCamelCase_ = vae_encoder.decode onnx_export( _a , model_args=( torch.randn(1 , _a , _a , _a ).to(device=_a , dtype=_a ), False, ) , output_path=output_path / "vae_decoder" / "model.onnx" , ordered_input_names=["latent_sample", "return_dict"] , output_names=["sample"] , dynamic_axes={ "latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, } , opset=_a , ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: lowerCamelCase_ = pipeline.safety_checker lowerCamelCase_ = safety_checker.config.vision_config.num_channels lowerCamelCase_ = safety_checker.config.vision_config.image_size lowerCamelCase_ = safety_checker.forward_onnx onnx_export( pipeline.safety_checker , model_args=( torch.randn( 1 , _a , _a , _a , ).to(device=_a , dtype=_a ), torch.randn(1 , _a , _a , _a ).to(device=_a , dtype=_a ), ) , output_path=output_path / "safety_checker" / "model.onnx" , ordered_input_names=["clip_input", "images"] , output_names=["out_images", "has_nsfw_concepts"] , dynamic_axes={ "clip_input": {0: "batch", 1: "channels", 2: "height", 3: "width"}, "images": {0: "batch", 1: "height", 2: "width", 3: "channels"}, } , opset=_a , ) del pipeline.safety_checker lowerCamelCase_ = OnnxRuntimeModel.from_pretrained(output_path / "safety_checker" ) lowerCamelCase_ = pipeline.feature_extractor else: lowerCamelCase_ = None lowerCamelCase_ = None lowerCamelCase_ = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_encoder" ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_decoder" ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / "text_encoder" ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / "unet" ) , scheduler=pipeline.scheduler , safety_checker=_a , feature_extractor=_a , requires_safety_checker=safety_checker is not None , ) onnx_pipeline.save_pretrained(_a ) print("ONNX pipeline saved to" , _a ) del pipeline del onnx_pipeline lowerCamelCase_ = OnnxStableDiffusionPipeline.from_pretrained(_a , provider="CPUExecutionProvider" ) print("ONNX pipeline is loadable" ) if __name__ == "__main__": __A =argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=1_4, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') __A =parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
19
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Dict = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : int = ya SCREAMING_SNAKE_CASE : int = xa for k in range(_a): SCREAMING_SNAKE_CASE : Any = y[k] + step_size * ode_func(_a , y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
76
0
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __lowerCAmelCase = '''\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } ''' __lowerCAmelCase = '''\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy. ''' __lowerCAmelCase = r''' Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting "1/2" to "\\frac{1}{2}") Examples: >>> metric = datasets.load_metric("competition_math") >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"]) >>> print(results) {\'accuracy\': 1.0} ''' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): def __lowercase ( self : Optional[int] ): 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 __lowercase ( self : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any] ): _a : Any = 0.0 for i, j in zip(_UpperCAmelCase ,_UpperCAmelCase ): n_correct += 1.0 if math_equivalence.is_equiv(_UpperCAmelCase ,_UpperCAmelCase ) else 0.0 _a : str = n_correct / len(_UpperCAmelCase ) return { "accuracy": accuracy, }
352
'''simple docstring''' import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __magic_name__ ( unittest.TestCase ): def __lowercase ( self : int ,_UpperCAmelCase : int ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ): self.assertEqual(len(_UpperCAmelCase ) ,len(_UpperCAmelCase ) ) for a, b in zip(_UpperCAmelCase ,_UpperCAmelCase ): self.assertAlmostEqual(_UpperCAmelCase ,_UpperCAmelCase ,delta=_UpperCAmelCase ) def __lowercase ( self : int ): _a : int = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(_UpperCAmelCase ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step ,3 ) self.assertEqual(len(accumulator.gradients ) ,1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() ,[-2.0, 5.0] ,tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step ,0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() ,[0.0, 0.0] ,tol=1E-2 ) def __lowercase ( self : Any ): _a : int = None ops.enable_eager_execution_internal() _a : Optional[int] = tf.config.list_physical_devices('CPU' ) if len(_UpperCAmelCase ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] ,[tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) _a : Tuple = tf.config.list_logical_devices(device_type='CPU' ) _a : List[str] = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): _a : Tuple = GradientAccumulator() _a : List[Any] = tf.Variable([4.0, 3.0] ) _a , _a : Dict = create_optimizer(5E-5 ,10 ,5 ) _a : Tuple = tf.Variable([0.0, 0.0] ,trainable=_UpperCAmelCase ) def accumulate_on_replica(_UpperCAmelCase : str ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients ,[variable] ) ) ) @tf.function def accumulate(_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ): with strategy.scope(): _a : Union[str, Any] = strategy.experimental_local_results(_UpperCAmelCase ) local_variables[0].assign(_UpperCAmelCase ) local_variables[1].assign(_UpperCAmelCase ) strategy.run(_UpperCAmelCase ,args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(_UpperCAmelCase ) def _check_local_values(_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ): _a : List[Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() ,_UpperCAmelCase ,tol=1E-2 ) self.assertListAlmostEqual(values[1].value() ,_UpperCAmelCase ,tol=1E-2 ) accumulate([1.0, 2.0] ,[-1.0, 1.0] ) accumulate([3.0, -1.0] ,[-1.0, -1.0] ) accumulate([-2.0, 2.0] ,[3.0, -2.0] ) self.assertEqual(accumulator.step ,3 ) _check_local_values([2.0, 3.0] ,[1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() ,[4.0, 3.0] ,tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step ,0 ) _check_local_values([0.0, 0.0] ,[0.0, 0.0] )
107
0
'''simple docstring''' import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class a__ ( unittest.TestCase ): """simple docstring""" __UpperCamelCase : Optional[int] = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING __UpperCamelCase : str = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def _snake_case (self , __lowercase , __lowercase , __lowercase ): __lowerCAmelCase = AudioClassificationPipeline(model=__lowerCAmelCase , feature_extractor=__lowerCAmelCase ) # test with a raw waveform __lowerCAmelCase = np.zeros((3_40_00,) ) __lowerCAmelCase = np.zeros((1_40_00,) ) return audio_classifier, [audioa, audio] def _snake_case (self , __lowercase , __lowercase ): __lowerCAmelCase , __lowerCAmelCase = examples __lowerCAmelCase = audio_classifier(__lowerCAmelCase ) # by default a model is initialized with num_labels=2 self.assertEqual( __lowerCAmelCase , [ {'''score''': ANY(__lowerCAmelCase ), '''label''': ANY(__lowerCAmelCase )}, {'''score''': ANY(__lowerCAmelCase ), '''label''': ANY(__lowerCAmelCase )}, ] , ) __lowerCAmelCase = audio_classifier(__lowerCAmelCase , top_k=1 ) self.assertEqual( __lowerCAmelCase , [ {'''score''': ANY(__lowerCAmelCase ), '''label''': ANY(__lowerCAmelCase )}, ] , ) self.run_torchaudio(__lowerCAmelCase ) @require_torchaudio def _snake_case (self , __lowercase ): import datasets # test with a local file __lowerCAmelCase = datasets.load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) __lowerCAmelCase = dataset[0]['''audio''']['''array'''] __lowerCAmelCase = audio_classifier(__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ {'''score''': ANY(__lowerCAmelCase ), '''label''': ANY(__lowerCAmelCase )}, {'''score''': ANY(__lowerCAmelCase ), '''label''': ANY(__lowerCAmelCase )}, ] , ) @require_torch def _snake_case (self ): __lowerCAmelCase = '''anton-l/wav2vec2-random-tiny-classifier''' __lowerCAmelCase = pipeline('''audio-classification''' , model=__lowerCAmelCase ) __lowerCAmelCase = np.ones((80_00,) ) __lowerCAmelCase = audio_classifier(__lowerCAmelCase , top_k=4 ) __lowerCAmelCase = [ {'''score''': 0.0_8_4_2, '''label''': '''no'''}, {'''score''': 0.0_8_3_8, '''label''': '''up'''}, {'''score''': 0.0_8_3_7, '''label''': '''go'''}, {'''score''': 0.0_8_3_4, '''label''': '''right'''}, ] __lowerCAmelCase = [ {'''score''': 0.0_8_4_5, '''label''': '''stop'''}, {'''score''': 0.0_8_4_4, '''label''': '''on'''}, {'''score''': 0.0_8_4_1, '''label''': '''right'''}, {'''score''': 0.0_8_3_4, '''label''': '''left'''}, ] self.assertIn(nested_simplify(__lowerCAmelCase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) __lowerCAmelCase = {'''array''': np.ones((80_00,) ), '''sampling_rate''': audio_classifier.feature_extractor.sampling_rate} __lowerCAmelCase = audio_classifier(__lowerCAmelCase , top_k=4 ) self.assertIn(nested_simplify(__lowerCAmelCase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def _snake_case (self ): import datasets __lowerCAmelCase = '''superb/wav2vec2-base-superb-ks''' __lowerCAmelCase = pipeline('''audio-classification''' , model=__lowerCAmelCase ) __lowerCAmelCase = datasets.load_dataset('''anton-l/superb_dummy''' , '''ks''' , split='''test''' ) __lowerCAmelCase = np.array(dataset[3]['''speech'''] , dtype=np.floataa ) __lowerCAmelCase = audio_classifier(__lowerCAmelCase , top_k=4 ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=3 ) , [ {'''score''': 0.9_8_1, '''label''': '''go'''}, {'''score''': 0.0_0_7, '''label''': '''up'''}, {'''score''': 0.0_0_6, '''label''': '''_unknown_'''}, {'''score''': 0.0_0_1, '''label''': '''down'''}, ] , ) @require_tf @unittest.skip('''Audio classification is not implemented for TF''' ) def _snake_case (self ): pass
174
"""simple docstring""" import argparse import json import subprocess def UpperCAmelCase__ ( lowerCAmelCase__ :Tuple , lowerCAmelCase__ :List[Any] ) -> Optional[Any]: '''simple docstring''' lowercase = [] lowercase = ( f'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"' """ https://api.github.com/repos/huggingface/transformers/actions/runners""" ) lowercase = subprocess.run(lowerCAmelCase__ , shell=lowerCAmelCase__ , stdout=subprocess.PIPE ) lowercase = output.stdout.decode("""utf-8""" ) lowercase = json.loads(lowerCAmelCase__ ) lowercase = status["""runners"""] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(lowerCAmelCase__ ) # save the result so we can report them on Slack with open("""offline_runners.txt""" , """w""" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) ) if len(lowerCAmelCase__ ) > 0: lowercase = """\n""".join([x["""name"""] for x in offline_runners] ) raise ValueError(f'The following runners are offline:\n{failed}' ) if __name__ == "__main__": def UpperCAmelCase__ ( lowerCAmelCase__ :Optional[int] ) -> Tuple: '''simple docstring''' return values.split(""",""" ) __lowerCAmelCase : str =argparse.ArgumentParser() # Required parameters parser.add_argument( """--target_runners""", default=None, type=list_str, required=True, help="""Comma-separated list of runners to check status.""", ) parser.add_argument( """--token""", default=None, type=str, required=True, help="""A token that has actions:read permission.""" ) __lowerCAmelCase : str =parser.parse_args() get_runner_status(args.target_runners, args.token)
197
0
'''simple docstring''' import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class a__ ( a__ ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self ) -> List[str]: lowerCAmelCase__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase_ , '''hidden_sizes''' ) ) self.parent.assertTrue(hasattr(lowerCamelCase_ , '''num_attention_heads''' ) ) self.parent.assertTrue(hasattr(lowerCamelCase_ , '''num_encoder_blocks''' ) ) class a__ : '''simple docstring''' def __init__( self , lowerCamelCase_ , lowerCamelCase_=13 , lowerCamelCase_=64 , lowerCamelCase_=3 , lowerCamelCase_=4 , lowerCamelCase_=[2, 2, 2, 2] , lowerCamelCase_=[8, 4, 2, 1] , lowerCamelCase_=[16, 32, 64, 1_28] , lowerCamelCase_=[1, 4, 8, 16] , lowerCamelCase_=[1, 2, 4, 8] , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=0.02 , lowerCamelCase_=3 , lowerCamelCase_=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = num_encoder_blocks lowerCAmelCase__ = sr_ratios lowerCAmelCase__ = depths lowerCAmelCase__ = hidden_sizes lowerCAmelCase__ = downsampling_rates lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_labels lowerCAmelCase__ = scope def __SCREAMING_SNAKE_CASE ( self ) -> str: lowerCAmelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]: lowerCAmelCase__ = SegformerModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() lowerCAmelCase__ = model(lowerCamelCase_ ) lowerCAmelCase__ = lowerCAmelCase__ = self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> str: lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = SegformerForSemanticSegmentation(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() lowerCAmelCase__ = model(lowerCamelCase_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) lowerCAmelCase__ = model(lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Dict: lowerCAmelCase__ = 1 lowerCAmelCase__ = SegformerForSemanticSegmentation(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() lowerCAmelCase__ = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(lowerCamelCase_ ) lowerCAmelCase__ = model(lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertGreater(result.loss , 0.0 ) def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a__ ( a__ , a__ , unittest.TestCase ): '''simple docstring''' lowercase__ : Optional[int] = ( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) lowercase__ : Dict = ( { "feature-extraction": SegformerModel, "image-classification": SegformerForImageClassification, "image-segmentation": SegformerForSemanticSegmentation, } if is_torch_available() else {} ) lowercase__ : str = True lowercase__ : str = False lowercase__ : str = False lowercase__ : Any = False def __SCREAMING_SNAKE_CASE ( self ) -> Dict: lowerCAmelCase__ = SegformerModelTester(self ) lowerCAmelCase__ = SegformerConfigTester(self , config_class=lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self ) -> Dict: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self ) -> int: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*lowerCamelCase_ ) @unittest.skip('''SegFormer does not use inputs_embeds''' ) def __SCREAMING_SNAKE_CASE ( self ) -> Dict: pass @unittest.skip('''SegFormer does not have get_input_embeddings method and get_output_embeddings methods''' ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: pass def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(lowerCamelCase_ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) lowerCAmelCase__ = outputs.attentions lowerCAmelCase__ = sum(self.model_tester.depths ) self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # verify the first attentions (first block, first layer) lowerCAmelCase__ = (self.model_tester.image_size // 4) ** 2 lowerCAmelCase__ = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) lowerCAmelCase__ = (self.model_tester.image_size // 32) ** 2 lowerCAmelCase__ = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) lowerCAmelCase__ = len(lowerCamelCase_ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(out_len + 1 , len(lowerCamelCase_ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # verify the first attentions (first block, first layer) lowerCAmelCase__ = (self.model_tester.image_size // 4) ** 2 lowerCAmelCase__ = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def __SCREAMING_SNAKE_CASE ( self ) -> str: def check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase__ = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_encoder_blocks self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: if not self.model_tester.is_training: return lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: if model_class in get_values(lowerCamelCase_ ): continue lowerCAmelCase__ = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.train() lowerCAmelCase__ = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ , return_labels=lowerCamelCase_ ) lowerCAmelCase__ = model(**lowerCamelCase_ ).loss loss.backward() @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: pass @slow def __SCREAMING_SNAKE_CASE ( self ) -> List[str]: for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = SegformerModel.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) def _snake_case ( ) -> str: lowerCAmelCase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch class a__ ( unittest.TestCase ): '''simple docstring''' @slow def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: # only resize + normalize lowerCAmelCase__ = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=lowerCamelCase_ , align=lowerCamelCase_ , do_random_crop=lowerCamelCase_ ) lowerCAmelCase__ = SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512''' ).to( lowerCamelCase_ ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=lowerCamelCase_ , return_tensors='''pt''' ) lowerCAmelCase__ = encoded_inputs.pixel_values.to(lowerCamelCase_ ) with torch.no_grad(): lowerCAmelCase__ = model(lowerCamelCase_ ) lowerCAmelCase__ = torch.Size((1, model.config.num_labels, 1_28, 1_28) ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) lowerCAmelCase__ = torch.tensor( [ [[-4.6_310, -5.5_232, -6.2_356], [-5.1_921, -6.1_444, -6.5_996], [-5.4_424, -6.2_790, -6.7_574]], [[-12.1_391, -13.3_122, -13.9_554], [-12.8_732, -13.9_352, -14.3_563], [-12.9_438, -13.8_226, -14.2_513]], [[-12.5_134, -13.4_686, -14.4_915], [-12.8_669, -14.4_343, -14.7_758], [-13.2_523, -14.5_819, -15.0_694]], ] ).to(lowerCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , lowerCamelCase_ , atol=1e-4 ) ) @slow def __SCREAMING_SNAKE_CASE ( self ) -> str: # only resize + normalize lowerCAmelCase__ = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=lowerCamelCase_ , align=lowerCamelCase_ , do_random_crop=lowerCamelCase_ ) lowerCAmelCase__ = SegformerForSemanticSegmentation.from_pretrained( '''nvidia/segformer-b1-finetuned-cityscapes-1024-1024''' ).to(lowerCamelCase_ ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=lowerCamelCase_ , return_tensors='''pt''' ) lowerCAmelCase__ = encoded_inputs.pixel_values.to(lowerCamelCase_ ) with torch.no_grad(): lowerCAmelCase__ = model(lowerCamelCase_ ) lowerCAmelCase__ = torch.Size((1, model.config.num_labels, 1_28, 1_28) ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) lowerCAmelCase__ = torch.tensor( [ [[-13.5_748, -13.9_111, -12.6_500], [-14.3_500, -15.3_683, -14.2_328], [-14.7_532, -16.0_424, -15.6_087]], [[-17.1_651, -15.8_725, -12.9_653], [-17.2_580, -17.3_718, -14.8_223], [-16.6_058, -16.8_783, -16.7_452]], [[-3.6_456, -3.0_209, -1.4_203], [-3.0_797, -3.1_959, -2.0_000], [-1.8_757, -1.9_217, -1.6_997]], ] ).to(lowerCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , lowerCamelCase_ , atol=1e-1 ) ) @slow def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: # only resize + normalize lowerCAmelCase__ = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=lowerCamelCase_ , align=lowerCamelCase_ , do_random_crop=lowerCamelCase_ ) lowerCAmelCase__ = SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512''' ).to( lowerCamelCase_ ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=lowerCamelCase_ , return_tensors='''pt''' ) lowerCAmelCase__ = encoded_inputs.pixel_values.to(lowerCamelCase_ ) with torch.no_grad(): lowerCAmelCase__ = model(lowerCamelCase_ ) lowerCAmelCase__ = outputs.logits.detach().cpu() lowerCAmelCase__ = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_ , target_sizes=[(5_00, 3_00)] ) lowerCAmelCase__ = torch.Size((5_00, 3_00) ) self.assertEqual(segmentation[0].shape , lowerCamelCase_ ) lowerCAmelCase__ = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_ ) lowerCAmelCase__ = torch.Size((1_28, 1_28) ) self.assertEqual(segmentation[0].shape , lowerCamelCase_ )
228
'''simple docstring''' def _snake_case ( A = 10 , A = 22 ) -> int: lowerCAmelCase__ = range(1 , A ) lowerCAmelCase__ = 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) = }""")
228
1
"""simple docstring""" from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def _snake_case ( lowercase__ ): if isinstance(lowercase__ , collections.abc.Iterable ): return x return (x, x) @require_tf class lowerCAmelCase__ : '''simple docstring''' def A_ ( self , lowercase , lowercase ): pass def A_ ( self ): pass def A_ ( self ): pass def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase=None , **lowercase ): _lowerCamelCase : Tuple = VisionTextDualEncoderConfig.from_vision_text_configs(lowercase , lowercase ) _lowerCamelCase : int = TFVisionTextDualEncoderModel(lowercase ) _lowerCamelCase : Optional[Any] = model(input_ids=lowercase , pixel_values=lowercase , attention_mask=lowercase ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase=None , **lowercase ): _lowerCamelCase, _lowerCamelCase : Dict = self.get_vision_text_model(lowercase , lowercase ) _lowerCamelCase : Optional[Any] = TFVisionTextDualEncoderModel(vision_model=lowercase , text_model=lowercase ) _lowerCamelCase : List[str] = model(input_ids=lowercase , pixel_values=lowercase , attention_mask=lowercase ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase=None , **lowercase ): _lowerCamelCase, _lowerCamelCase : List[Any] = self.get_vision_text_model(lowercase , lowercase ) _lowerCamelCase : Tuple = {'vision_model': vision_model, 'text_model': text_model} _lowerCamelCase : Dict = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase ) _lowerCamelCase : Dict = model(input_ids=lowercase , pixel_values=lowercase , attention_mask=lowercase ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase=None , **lowercase ): _lowerCamelCase, _lowerCamelCase : int = self.get_vision_text_model(lowercase , lowercase ) _lowerCamelCase : List[Any] = TFVisionTextDualEncoderModel(vision_model=lowercase , text_model=lowercase ) _lowerCamelCase : Union[str, Any] = model(input_ids=lowercase , pixel_values=lowercase , attention_mask=lowercase ) _lowerCamelCase : Union[str, Any] = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase ) _lowerCamelCase : List[Any] = TFVisionTextDualEncoderModel.from_pretrained(lowercase ) _lowerCamelCase : Tuple = model(input_ids=lowercase , pixel_values=lowercase , attention_mask=lowercase ) _lowerCamelCase : List[str] = after_output[0].numpy() _lowerCamelCase : Optional[int] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase , 1E-5 ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase=None , **lowercase ): _lowerCamelCase, _lowerCamelCase : List[Any] = self.get_vision_text_model(lowercase , lowercase ) _lowerCamelCase : List[str] = TFVisionTextDualEncoderModel(vision_model=lowercase , text_model=lowercase ) _lowerCamelCase : Tuple = model( input_ids=lowercase , pixel_values=lowercase , attention_mask=lowercase , output_attentions=lowercase ) _lowerCamelCase : List[Any] = output.vision_model_output.attentions self.assertEqual(len(lowercase ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) _lowerCamelCase : Any = to_atuple(vision_model.config.image_size ) _lowerCamelCase : List[Any] = to_atuple(vision_model.config.patch_size ) _lowerCamelCase : Optional[int] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) _lowerCamelCase : Tuple = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) _lowerCamelCase : Union[str, Any] = output.text_model_output.attentions self.assertEqual(len(lowercase ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def A_ ( self , lowercase , lowercase , lowercase ): _lowerCamelCase : Tuple = np.abs((a - b) ).max() self.assertLessEqual(lowercase , lowercase , F'''Difference between torch and flax is {diff} (>= {tol}).''' ) def A_ ( self ): _lowerCamelCase : Any = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**lowercase ) def A_ ( self ): _lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowercase ) def A_ ( self ): _lowerCamelCase : Optional[int] = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowercase ) def A_ ( self ): _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() self.check_save_load(**lowercase ) def A_ ( self ): _lowerCamelCase : Any = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowercase ) @slow def A_ ( self ): _lowerCamelCase, _lowerCamelCase : int = self.get_pretrained_model_and_inputs() _lowerCamelCase : str = model_a(**lowercase ) _lowerCamelCase : List[Any] = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowercase ) _lowerCamelCase : List[Any] = TFVisionTextDualEncoderModel.from_pretrained(lowercase ) _lowerCamelCase : Union[str, Any] = model_a(**lowercase ) _lowerCamelCase : Optional[Any] = after_outputs[0].numpy() _lowerCamelCase : Tuple = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase , 1E-5 ) @require_tf class lowerCAmelCase__ ( lowercase, unittest.TestCase ): '''simple docstring''' def A_ ( self ): _lowerCamelCase : Optional[Any] = TFVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-random-bert' ) _lowerCamelCase : Tuple = 13 _lowerCamelCase : Tuple = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) _lowerCamelCase : Dict = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) _lowerCamelCase : int = random_attention_mask([batch_size, 4] ) _lowerCamelCase : Any = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def A_ ( self , lowercase , lowercase ): _lowerCamelCase : int = TFViTModel(lowercase , name='vision_model' ) _lowerCamelCase : Union[str, Any] = TFBertModel(lowercase , name='text_model' ) return vision_model, text_model def A_ ( self ): _lowerCamelCase : Optional[int] = TFViTModelTester(self ) _lowerCamelCase : str = TFBertModelTester(self ) _lowerCamelCase : int = vit_model_tester.prepare_config_and_inputs() _lowerCamelCase : str = bert_model_tester.prepare_config_and_inputs() _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Dict = vision_config_and_inputs ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : Union[str, Any] = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class lowerCAmelCase__ ( lowercase, unittest.TestCase ): '''simple docstring''' def A_ ( self ): # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's # just reinitialize it. _lowerCamelCase : int = TFVisionTextDualEncoderModel.from_vision_text_pretrained( 'Rocketknight1/tiny-random-deit-tf' , 'hf-internal-testing/tiny-random-roberta' ) _lowerCamelCase : Tuple = 13 _lowerCamelCase : Tuple = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) _lowerCamelCase : Tuple = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) _lowerCamelCase : str = random_attention_mask([batch_size, 4] ) _lowerCamelCase : Optional[Any] = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase=None , **lowercase ): _lowerCamelCase, _lowerCamelCase : Union[str, Any] = self.get_vision_text_model(lowercase , lowercase ) _lowerCamelCase : Dict = TFVisionTextDualEncoderModel(vision_model=lowercase , text_model=lowercase ) _lowerCamelCase : List[Any] = model( input_ids=lowercase , pixel_values=lowercase , attention_mask=lowercase , output_attentions=lowercase ) _lowerCamelCase : Union[str, Any] = output.vision_model_output.attentions self.assertEqual(len(lowercase ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _lowerCamelCase : Any = to_atuple(vision_model.config.image_size ) _lowerCamelCase : Union[str, Any] = to_atuple(vision_model.config.patch_size ) _lowerCamelCase : Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) _lowerCamelCase : Optional[int] = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) _lowerCamelCase : List[Any] = output.text_model_output.attentions self.assertEqual(len(lowercase ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def A_ ( self , lowercase , lowercase ): _lowerCamelCase : List[Any] = TFDeiTModel(lowercase , name='vision_model' ) _lowerCamelCase : List[str] = TFRobertaModel(lowercase , name='text_model' ) return vision_model, text_model def A_ ( self ): _lowerCamelCase : Any = TFDeiTModelTester(self ) _lowerCamelCase : Union[str, Any] = TFRobertaModelTester(self ) _lowerCamelCase : Optional[int] = vit_model_tester.prepare_config_and_inputs() _lowerCamelCase : int = bert_model_tester.prepare_config_and_inputs() _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Dict = vision_config_and_inputs ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : Dict = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class lowerCAmelCase__ ( lowercase, unittest.TestCase ): '''simple docstring''' def A_ ( self ): _lowerCamelCase : Dict = TFVisionTextDualEncoderModel.from_vision_text_pretrained( 'Rocketknight1/tiny-random-clip-tf' , 'hf-internal-testing/tiny-random-bert' ) _lowerCamelCase : Any = 13 _lowerCamelCase : List[Any] = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) _lowerCamelCase : Any = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) _lowerCamelCase : List[Any] = random_attention_mask([batch_size, 4] ) _lowerCamelCase : List[Any] = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def A_ ( self , lowercase , lowercase ): _lowerCamelCase : Optional[int] = TFCLIPVisionModel(lowercase , name='vision_model' ) _lowerCamelCase : List[str] = TFBertModel(lowercase , name='text_model' ) return vision_model, text_model def A_ ( self ): _lowerCamelCase : Union[str, Any] = TFCLIPVisionModelTester(self ) _lowerCamelCase : Optional[Any] = TFBertModelTester(self ) _lowerCamelCase : str = clip_model_tester.prepare_config_and_inputs() _lowerCamelCase : Optional[int] = bert_model_tester.prepare_config_and_inputs() _lowerCamelCase, _lowerCamelCase : List[Any] = vision_config_and_inputs ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : List[str] = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def A_ ( self ): _lowerCamelCase : List[str] = TFVisionTextDualEncoderModel.from_pretrained( 'clip-italian/clip-italian' , logit_scale_init_value=1.0 , from_pt=lowercase ) _lowerCamelCase : str = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) _lowerCamelCase : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) _lowerCamelCase : List[Any] = processor( text=['una foto di un gatto', 'una foto di un cane'] , images=lowercase , padding=lowercase , return_tensors='np' ) _lowerCamelCase : List[Any] = model(**lowercase ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) _lowerCamelCase : int = np.array([[1.2_28_47_27, 0.3_10_41_22]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , lowercase , atol=1E-3 ) )
96
def lowerCAmelCase ( lowerCAmelCase_ = 10**9 )-> int: lowerCAmelCase_ : List[Any] = 1 lowerCAmelCase_ : Optional[int] = 2 lowerCAmelCase_ : Any = 0 lowerCAmelCase_ : str = 0 lowerCAmelCase_ : str = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value lowerCAmelCase_ : Any = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f"""{solution() = }""")
262
0
"""simple docstring""" from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = CustomTokenizer pass
369
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __A = logging.get_logger(__name__) __A = { """microsoft/swin-tiny-patch4-window7-224""": ( """https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json""" ), # See all Swin models at https://huggingface.co/models?filter=swin } class _lowerCAmelCase ( a , a ): """simple docstring""" __magic_name__ :int = """swin""" __magic_name__ :Tuple = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , __UpperCAmelCase=2_2_4 , __UpperCAmelCase=4 , __UpperCAmelCase=3 , __UpperCAmelCase=9_6 , __UpperCAmelCase=[2, 2, 6, 2] , __UpperCAmelCase=[3, 6, 1_2, 2_4] , __UpperCAmelCase=7 , __UpperCAmelCase=4.0 , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase="gelu" , __UpperCAmelCase=False , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=3_2 , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) lowerCAmelCase__ :Any = image_size lowerCAmelCase__ :List[Any] = patch_size lowerCAmelCase__ :Optional[int] = num_channels lowerCAmelCase__ :str = embed_dim lowerCAmelCase__ :Optional[int] = depths lowerCAmelCase__ :List[str] = len(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = num_heads lowerCAmelCase__ :List[Any] = window_size lowerCAmelCase__ :List[Any] = mlp_ratio lowerCAmelCase__ :int = qkv_bias lowerCAmelCase__ :Optional[int] = hidden_dropout_prob lowerCAmelCase__ :int = attention_probs_dropout_prob lowerCAmelCase__ :List[Any] = drop_path_rate lowerCAmelCase__ :Any = hidden_act lowerCAmelCase__ :Dict = use_absolute_embeddings lowerCAmelCase__ :int = layer_norm_eps lowerCAmelCase__ :Dict = initializer_range lowerCAmelCase__ :int = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowerCAmelCase__ :str = int(embed_dim * 2 ** (len(__UpperCAmelCase ) - 1) ) lowerCAmelCase__ :str = ['stem'] + [F"stage{idx}" for idx in range(1 , len(__UpperCAmelCase ) + 1 )] lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = get_aligned_output_features_output_indices( out_features=__UpperCAmelCase , out_indices=__UpperCAmelCase , stage_names=self.stage_names ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :int = version.parse("""1.11""" ) @property def snake_case ( self ): '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def snake_case ( self ): '''simple docstring''' return 1E-4
254
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging _lowercase : Optional[int] = logging.get_logger(__name__) _lowercase : Any = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''umt5''' lowerCAmelCase_ = ['''past_key_values'''] def __init__( self , __SCREAMING_SNAKE_CASE=25_01_12 , __SCREAMING_SNAKE_CASE=5_12 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=10_24 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gated-gelu" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="T5Tokenizer" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__( is_encoder_decoder=__SCREAMING_SNAKE_CASE , tokenizer_class=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : List[str] = vocab_size lowercase_ : Optional[Any] = d_model lowercase_ : str = d_kv lowercase_ : Any = d_ff lowercase_ : Optional[Any] = num_layers lowercase_ : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowercase_ : Optional[Any] = num_heads lowercase_ : int = relative_attention_num_buckets lowercase_ : Tuple = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : List[str] = layer_norm_epsilon lowercase_ : str = initializer_factor lowercase_ : int = feed_forward_proj lowercase_ : Optional[Any] = use_cache lowercase_ : Optional[Any] = self.feed_forward_proj.split('''-''' ) lowercase_ : List[str] = act_info[-1] lowercase_ : List[str] = act_info[0] == '''gated''' if len(__SCREAMING_SNAKE_CASE ) > 1 and act_info[0] != "gated" or len(__SCREAMING_SNAKE_CASE ) > 2: raise ValueError( F'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) if feed_forward_proj == "gated-gelu": lowercase_ : int = '''gelu_new''' @property def _snake_case ( self ): """simple docstring""" return self.d_model @property def _snake_case ( self ): """simple docstring""" return self.num_heads @property def _snake_case ( self ): """simple docstring""" return self.num_layers class lowerCAmelCase__ ( lowerCamelCase_ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: lowercase_ : str = '''past_encoder_sequence + sequence''' lowercase_ : Optional[int] = {0: '''batch'''} lowercase_ : List[str] = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: lowercase_ : List[Any] = {0: '''batch''', 1: '''decoder_sequence'''} lowercase_ : Optional[Any] = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__SCREAMING_SNAKE_CASE , direction='''inputs''' ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def _snake_case ( self ): """simple docstring""" return 13 @property def _snake_case ( self ): """simple docstring""" return 5E-4
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
1
import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" if gpta_config_file == "": _lowerCAmelCase = GPTaConfig() else: _lowerCAmelCase = GPTaConfig.from_json_file(__snake_case ) _lowerCAmelCase = GPTaModel(__snake_case ) # Load weights from numpy load_tf_weights_in_gpta(__snake_case , __snake_case , __snake_case ) # Save pytorch-model _lowerCAmelCase = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _lowerCAmelCase = pytorch_dump_folder_path + """/""" + CONFIG_NAME print(f"Save PyTorch model to {pytorch_weights_dump_path}" ) torch.save(model.state_dict() , __snake_case ) print(f"Save configuration file to {pytorch_config_dump_path}" ) with open(__snake_case , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A__ : Any =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--gpt2_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow 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( '''--gpt2_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained OpenAI model. \n''' '''This specifies the model architecture.''' ), ) A__ : List[Any] =parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
356
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase ( unittest.TestCase ): def lowercase__ ( self : int ) -> Union[str, Any]: _lowerCAmelCase = inspect.getfile(accelerate.test_utils ) _lowerCAmelCase = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps""", """test_metrics.py"""] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 _lowerCAmelCase = test_metrics @require_cpu def lowercase__ ( self : Optional[Any] ) -> Optional[Any]: debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def lowercase__ ( self : Tuple ) -> Tuple: debug_launcher(self.test_metrics.main ) @require_single_gpu def lowercase__ ( self : Union[str, Any] ) -> str: self.test_metrics.main() @require_multi_gpu def lowercase__ ( self : str ) -> List[str]: print(f"Found {torch.cuda.device_count()} devices." ) _lowerCAmelCase = ["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__snake_case , env=os.environ.copy() )
220
0
'''simple docstring''' from typing import Dict, Optional import numpy as np import datasets _UpperCamelCase : Optional[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' _UpperCamelCase : List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' _UpperCamelCase : Optional[int] = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def __UpperCAmelCase ( A : Any , A : Optional[int] , A : List[str] , A : List[Any] , A : str = None , A : Tuple = False , ) -> int: if label_map is not None: for old_id, new_id in label_map.items(): UpperCAmelCase_ : Optional[int] = new_id # turn into Numpy arrays UpperCAmelCase_ : Dict = np.array(UpperCamelCase__ ) UpperCAmelCase_ : Any = np.array(UpperCamelCase__ ) if reduce_labels: UpperCAmelCase_ : Optional[Any] = 2_5_5 UpperCAmelCase_ : List[Any] = label - 1 UpperCAmelCase_ : Any = 2_5_5 UpperCAmelCase_ : Dict = label != ignore_index UpperCAmelCase_ : Optional[int] = np.not_equal(UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase_ : Tuple = pred_label[mask] UpperCAmelCase_ : Dict = np.array(UpperCamelCase__ )[mask] UpperCAmelCase_ : List[str] = pred_label[pred_label == label] UpperCAmelCase_ : Optional[Any] = np.histogram(UpperCamelCase__ , bins=UpperCamelCase__ , range=(0, num_labels - 1) )[0] UpperCAmelCase_ : Tuple = np.histogram(UpperCamelCase__ , bins=UpperCamelCase__ , range=(0, num_labels - 1) )[0] UpperCAmelCase_ : Optional[Any] = np.histogram(UpperCamelCase__ , bins=UpperCamelCase__ , range=(0, num_labels - 1) )[0] UpperCAmelCase_ : List[Any] = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def __UpperCAmelCase ( A : Tuple , A : Dict , A : Tuple , A : List[Any] , A : Optional[Any] = None , A : List[str] = False , ) -> int: UpperCAmelCase_ : Any = np.zeros((num_labels,) , dtype=np.floataa ) UpperCAmelCase_ : int = np.zeros((num_labels,) , dtype=np.floataa ) UpperCAmelCase_ : Optional[Any] = np.zeros((num_labels,) , dtype=np.floataa ) UpperCAmelCase_ : int = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase_ : List[Any] = intersect_and_union( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def __UpperCAmelCase ( A : Union[str, Any] , A : List[str] , A : Any , A : Union[str, Any] , A : Optional[int] = None , A : str = None , A : Tuple = False , ) -> Union[str, Any]: UpperCAmelCase_ : str = total_intersect_and_union( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # compute metrics UpperCAmelCase_ : Dict = {} UpperCAmelCase_ : int = total_area_intersect.sum() / total_area_label.sum() UpperCAmelCase_ : Tuple = total_area_intersect / total_area_union UpperCAmelCase_ : Any = total_area_intersect / total_area_label UpperCAmelCase_ : Union[str, Any] = np.nanmean(UpperCamelCase__ ) UpperCAmelCase_ : Optional[Any] = np.nanmean(UpperCamelCase__ ) UpperCAmelCase_ : Optional[int] = all_acc UpperCAmelCase_ : Dict = iou UpperCAmelCase_ : int = acc if nan_to_num is not None: UpperCAmelCase_ : str = {metric: np.nan_to_num(UpperCamelCase__ , nan=UpperCamelCase__ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class snake_case__ ( datasets.Metric): def A ( self : Union[str, Any] ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16''' ) ) ), '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16''' ) ) ), } ) , reference_urls=[ '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py''' ] , ) def A ( self : Optional[Any] , _A : List[str] , _A : int , _A : int , _A : Optional[Any] , _A : List[Any] = None , _A : str = None , _A : List[str] = False , ) -> Union[str, Any]: UpperCAmelCase_ : Optional[Any] = mean_iou( results=_lowerCamelCase , gt_seg_maps=_lowerCamelCase , num_labels=_lowerCamelCase , ignore_index=_lowerCamelCase , nan_to_num=_lowerCamelCase , label_map=_lowerCamelCase , reduce_labels=_lowerCamelCase , ) return iou_result
304
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) __A =logging.getLogger() def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Union[str, Any] = """\n""".join(UpperCamelCase__ ) Path(UpperCamelCase__ ).open("""w""" ).writelines(UpperCamelCase__ ) __A ='patrickvonplaten/t5-tiny-random' __A ='sshleifer/bart-tiny-random' __A ='sshleifer/tiny-mbart' __A =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class _snake_case ( a__ ): def snake_case__ ( self , _lowerCamelCase): UpperCAmelCase__ : Any = Path(self.get_auto_remove_tmp_dir()) / """utest_input.source""" UpperCAmelCase__ : Dict = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() UpperCAmelCase__ : Any = [""" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."""] _dump_articles(_lowerCamelCase , _lowerCamelCase) UpperCAmelCase__ : Optional[Any] = str(Path(self.get_auto_remove_tmp_dir()) / """scores.json""") UpperCAmelCase__ : int = """translation_en_to_de""" if model == T5_TINY else """summarization""" UpperCAmelCase__ : Union[str, Any] = f''' run_eval_search.py {model} {input_file_name} {output_file_name} --score_path {score_path} --task {task} --num_beams 2 --length_penalty 2.0 '''.split() with patch.object(_lowerCamelCase , """argv""" , _lowerCamelCase): run_generate() assert Path(_lowerCamelCase).exists() # os.remove(Path(output_file_name)) def snake_case__ ( self): self.run_eval_tester(_lowerCamelCase) @parameterized.expand([BART_TINY, MBART_TINY]) @slow def snake_case__ ( self , _lowerCamelCase): self.run_eval_tester(_lowerCamelCase) @parameterized.expand([T5_TINY, MBART_TINY]) @slow def snake_case__ ( self , _lowerCamelCase): UpperCAmelCase__ : Optional[Any] = Path(self.get_auto_remove_tmp_dir()) / """utest_input.source""" UpperCAmelCase__ : List[str] = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() UpperCAmelCase__ : int = { """en""": ["""Machine learning is great, isn't it?""", """I like to eat bananas""", """Tomorrow is another great day!"""], """de""": [ """Maschinelles Lernen ist großartig, oder?""", """Ich esse gerne Bananen""", """Morgen ist wieder ein toller Tag!""", ], } UpperCAmelCase__ : int = Path(self.get_auto_remove_tmp_dir()) UpperCAmelCase__ : Any = str(tmp_dir / """scores.json""") UpperCAmelCase__ : List[str] = str(tmp_dir / """val.target""") _dump_articles(_lowerCamelCase , text["""en"""]) _dump_articles(_lowerCamelCase , text["""de"""]) UpperCAmelCase__ : int = """translation_en_to_de""" if model == T5_TINY else """summarization""" UpperCAmelCase__ : List[Any] = f''' run_eval_search.py {model} {str(_lowerCamelCase)} {str(_lowerCamelCase)} --score_path {score_path} --reference_path {reference_path} --task {task} '''.split() testargs.extend(["""--search""", """num_beams=1:2 length_penalty=0.9:1.0"""]) with patch.object(_lowerCamelCase , """argv""" , _lowerCamelCase): with CaptureStdout() as cs: run_search() UpperCAmelCase__ : Optional[Any] = [""" num_beams | length_penalty""", model, """Best score args"""] UpperCAmelCase__ : Any = ["""Info"""] if "translation" in task: expected_strings.append("""bleu""") else: expected_strings.extend(_lowerCamelCase) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(_lowerCamelCase).exists() os.remove(Path(_lowerCamelCase))
163
0
'''simple docstring''' def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :int , lowerCAmelCase__ :list[list[int]] ) -> int: '''simple docstring''' def update_area_of_max_square(lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 _a = update_area_of_max_square(_SCREAMING_SNAKE_CASE , col + 1 ) _a = update_area_of_max_square(row + 1 , col + 1 ) _a = update_area_of_max_square(row + 1 , _SCREAMING_SNAKE_CASE ) if mat[row][col]: _a = 1 + min([right, diagonal, down] ) _a = max(largest_square_area[0] , _SCREAMING_SNAKE_CASE ) return sub_problem_sol else: return 0 _a = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :int , lowerCAmelCase__ :list[list[int]] ) -> int: '''simple docstring''' def update_area_of_max_square_using_dp_array( lowerCAmelCase__ :int , lowerCAmelCase__ :int , lowerCAmelCase__ :list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] _a = update_area_of_max_square_using_dp_array(_SCREAMING_SNAKE_CASE , col + 1 , _SCREAMING_SNAKE_CASE ) _a = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , _SCREAMING_SNAKE_CASE ) _a = update_area_of_max_square_using_dp_array(row + 1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if mat[row][col]: _a = 1 + min([right, diagonal, down] ) _a = max(largest_square_area[0] , _SCREAMING_SNAKE_CASE ) _a = sub_problem_sol return sub_problem_sol else: return 0 _a = [0] _a = [[-1] * cols for _ in range(_SCREAMING_SNAKE_CASE )] update_area_of_max_square_using_dp_array(0 , 0 , _SCREAMING_SNAKE_CASE ) return largest_square_area[0] def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :int , lowerCAmelCase__ :list[list[int]] ) -> int: '''simple docstring''' _a = [[0] * (cols + 1) for _ in range(rows + 1 )] _a = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): _a = dp_array[row][col + 1] _a = dp_array[row + 1][col + 1] _a = dp_array[row + 1][col] if mat[row][col] == 1: _a = 1 + min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _a = max(dp_array[row][col] , _SCREAMING_SNAKE_CASE ) else: _a = 0 return largest_square_area def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :int , lowerCAmelCase__ :list[list[int]] ) -> int: '''simple docstring''' _a = [0] * (cols + 1) _a = [0] * (cols + 1) _a = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): _a = current_row[col + 1] _a = next_row[col + 1] _a = next_row[col] if mat[row][col] == 1: _a = 1 + min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _a = max(current_row[col] , _SCREAMING_SNAKE_CASE ) else: _a = 0 _a = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
351
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ : str = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys a_ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
104
0
"""simple docstring""" from math import pow def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Optional[int]: '''simple docstring''' if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count lowercase_ = int(pow(__lowerCAmelCase , __lowerCAmelCase ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n lowercase_ = backtrack( __lowerCAmelCase , __lowerCAmelCase , current_number + 1 , __lowerCAmelCase , __lowerCAmelCase ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. lowercase_ = backtrack( __lowerCAmelCase , __lowerCAmelCase , current_number + 1 , __lowerCAmelCase , __lowerCAmelCase ) return current_sum, solutions_count def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> int: '''simple docstring''' if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10): raise ValueError( """Invalid input\n""" """needed_sum must be between 1 and 1000, power between 2 and 10.""" ) return backtrack(__lowerCAmelCase , __lowerCAmelCase , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
136
'''simple docstring''' from math import pow def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , ): if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count lowercase__ : Optional[Any] = int(pow(UpperCAmelCase , UpperCAmelCase ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n lowercase__ , lowercase__ : Dict = backtrack( UpperCAmelCase , UpperCAmelCase , current_number + 1 , UpperCAmelCase , UpperCAmelCase ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. lowercase__ , lowercase__ : str = backtrack( UpperCAmelCase , UpperCAmelCase , current_number + 1 , UpperCAmelCase , UpperCAmelCase ) return current_sum, solutions_count def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( '''Invalid input\n''' '''needed_sum must be between 1 and 1000, power between 2 and 10.''' ) return backtrack(UpperCAmelCase , UpperCAmelCase , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
198
0
from ...configuration_utils import PretrainedConfig class snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = """bert-generation""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE : Optional[int]=50_358 , SCREAMING_SNAKE_CASE : List[Any]=1_024 , SCREAMING_SNAKE_CASE : Optional[Any]=24 , SCREAMING_SNAKE_CASE : List[str]=16 , SCREAMING_SNAKE_CASE : Tuple=4_096 , SCREAMING_SNAKE_CASE : List[Any]="gelu" , SCREAMING_SNAKE_CASE : str=0.1 , SCREAMING_SNAKE_CASE : Any=0.1 , SCREAMING_SNAKE_CASE : Optional[int]=512 , SCREAMING_SNAKE_CASE : Tuple=0.02 , SCREAMING_SNAKE_CASE : Optional[int]=1E-1_2 , SCREAMING_SNAKE_CASE : List[Any]=0 , SCREAMING_SNAKE_CASE : List[str]=2 , SCREAMING_SNAKE_CASE : str=1 , SCREAMING_SNAKE_CASE : str="absolute" , SCREAMING_SNAKE_CASE : Optional[int]=True , **SCREAMING_SNAKE_CASE : str , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) lowercase__ : Any = vocab_size lowercase__ : Any = hidden_size lowercase__ : Tuple = num_hidden_layers lowercase__ : Union[str, Any] = num_attention_heads lowercase__ : Any = hidden_act lowercase__ : Dict = intermediate_size lowercase__ : List[str] = hidden_dropout_prob lowercase__ : Tuple = attention_probs_dropout_prob lowercase__ : int = max_position_embeddings lowercase__ : Optional[Any] = initializer_range lowercase__ : Tuple = layer_norm_eps lowercase__ : Dict = position_embedding_type lowercase__ : Union[str, Any] = use_cache
121
import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__=1 ): """simple docstring""" if n_shave_prefix_segments >= 0: return ".".join(path.split("." )[n_shave_prefix_segments:] ) else: return ".".join(path.split("." )[:n_shave_prefix_segments] ) def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__=0 ): """simple docstring""" lowercase__ : List[str] = [] for old_item in old_list: lowercase__ : Optional[Any] = old_item.replace("in_layers.0" , "norm1" ) lowercase__ : Union[str, Any] = new_item.replace("in_layers.2" , "conv1" ) lowercase__ : Optional[Any] = new_item.replace("out_layers.0" , "norm2" ) lowercase__ : Union[str, Any] = new_item.replace("out_layers.3" , "conv2" ) lowercase__ : Dict = new_item.replace("emb_layers.1" , "time_emb_proj" ) lowercase__ : int = new_item.replace("skip_connection" , "conv_shortcut" ) lowercase__ : Tuple = shave_segments(lowerCamelCase__ , n_shave_prefix_segments=lowerCamelCase__ ) mapping.append({"old": old_item, "new": new_item} ) return mapping def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__=0 ): """simple docstring""" lowercase__ : str = [] for old_item in old_list: lowercase__ : Optional[int] = old_item lowercase__ : Dict = new_item.replace("norm.weight" , "group_norm.weight" ) lowercase__ : Optional[int] = new_item.replace("norm.bias" , "group_norm.bias" ) lowercase__ : Tuple = new_item.replace("proj_out.weight" , "proj_attn.weight" ) lowercase__ : List[Any] = new_item.replace("proj_out.bias" , "proj_attn.bias" ) lowercase__ : Optional[Any] = shave_segments(lowerCamelCase__ , n_shave_prefix_segments=lowerCamelCase__ ) mapping.append({"old": old_item, "new": new_item} ) return mapping def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None ): """simple docstring""" assert isinstance(lowerCamelCase__ , lowerCamelCase__ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): lowercase__ : List[str] = old_checkpoint[path] lowercase__ : str = old_tensor.shape[0] // 3 lowercase__ : List[str] = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) lowercase__ : Union[str, Any] = old_tensor.shape[0] // config["num_head_channels"] // 3 lowercase__ : Union[str, Any] = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) lowercase__ , lowercase__ , lowercase__ : Optional[Any] = old_tensor.split(channels // num_heads , dim=1 ) lowercase__ : Dict = query.reshape(lowerCamelCase__ ) lowercase__ : Dict = key.reshape(lowerCamelCase__ ) lowercase__ : int = value.reshape(lowerCamelCase__ ) for path in paths: lowercase__ : Union[str, Any] = path["new"] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here lowercase__ : List[Any] = new_path.replace("middle_block.0" , "mid_block.resnets.0" ) lowercase__ : Optional[Any] = new_path.replace("middle_block.1" , "mid_block.attentions.0" ) lowercase__ : List[str] = new_path.replace("middle_block.2" , "mid_block.resnets.1" ) if additional_replacements is not None: for replacement in additional_replacements: lowercase__ : Tuple = new_path.replace(replacement["old"] , replacement["new"] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: lowercase__ : List[Any] = old_checkpoint[path["old"]][:, :, 0] else: lowercase__ : List[Any] = old_checkpoint[path["old"]] def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" lowercase__ : Union[str, Any] = {} lowercase__ : Optional[Any] = checkpoint["time_embed.0.weight"] lowercase__ : Tuple = checkpoint["time_embed.0.bias"] lowercase__ : Dict = checkpoint["time_embed.2.weight"] lowercase__ : Optional[Any] = checkpoint["time_embed.2.bias"] lowercase__ : Optional[int] = checkpoint["input_blocks.0.0.weight"] lowercase__ : List[Any] = checkpoint["input_blocks.0.0.bias"] lowercase__ : Tuple = checkpoint["out.0.weight"] lowercase__ : List[Any] = checkpoint["out.0.bias"] lowercase__ : Tuple = checkpoint["out.2.weight"] lowercase__ : Optional[Any] = checkpoint["out.2.bias"] # Retrieves the keys for the input blocks only lowercase__ : Dict = len({".".join(layer.split("." )[:2] ) for layer in checkpoint if "input_blocks" in layer} ) lowercase__ : str = { layer_id: [key for key in checkpoint if F"""input_blocks.{layer_id}""" in key] for layer_id in range(lowerCamelCase__ ) } # Retrieves the keys for the middle blocks only lowercase__ : Tuple = len({".".join(layer.split("." )[:2] ) for layer in checkpoint if "middle_block" in layer} ) lowercase__ : Union[str, Any] = { layer_id: [key for key in checkpoint if F"""middle_block.{layer_id}""" in key] for layer_id in range(lowerCamelCase__ ) } # Retrieves the keys for the output blocks only lowercase__ : Tuple = len({".".join(layer.split("." )[:2] ) for layer in checkpoint if "output_blocks" in layer} ) lowercase__ : Tuple = { layer_id: [key for key in checkpoint if F"""output_blocks.{layer_id}""" in key] for layer_id in range(lowerCamelCase__ ) } for i in range(1 , lowerCamelCase__ ): lowercase__ : Tuple = (i - 1) // (config["num_res_blocks"] + 1) lowercase__ : Optional[int] = (i - 1) % (config["num_res_blocks"] + 1) lowercase__ : List[Any] = [key for key in input_blocks[i] if F"""input_blocks.{i}.0""" in key] lowercase__ : Dict = [key for key in input_blocks[i] if F"""input_blocks.{i}.1""" in key] if F"""input_blocks.{i}.0.op.weight""" in checkpoint: lowercase__ : int = checkpoint[ F"""input_blocks.{i}.0.op.weight""" ] lowercase__ : List[str] = checkpoint[ F"""input_blocks.{i}.0.op.bias""" ] continue lowercase__ : Union[str, Any] = renew_resnet_paths(lowerCamelCase__ ) lowercase__ : Optional[int] = {"old": F"""input_blocks.{i}.0""", "new": F"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} lowercase__ : Optional[int] = {"old": "resnets.2.op", "new": "downsamplers.0.op"} assign_to_checkpoint( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path, resnet_op] , config=lowerCamelCase__ ) if len(lowerCamelCase__ ): lowercase__ : Tuple = renew_attention_paths(lowerCamelCase__ ) lowercase__ : str = { "old": F"""input_blocks.{i}.1""", "new": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } lowercase__ : List[str] = { F"""input_blocks.{i}.1.qkv.bias""": { "key": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", "query": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", "value": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, F"""input_blocks.{i}.1.qkv.weight""": { "key": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", "query": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", "value": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCamelCase__ , config=lowerCamelCase__ , ) lowercase__ : int = middle_blocks[0] lowercase__ : Dict = middle_blocks[1] lowercase__ : Dict = middle_blocks[2] lowercase__ : Any = renew_resnet_paths(lowerCamelCase__ ) assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , config=lowerCamelCase__ ) lowercase__ : List[Any] = renew_resnet_paths(lowerCamelCase__ ) assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , config=lowerCamelCase__ ) lowercase__ : Optional[int] = renew_attention_paths(lowerCamelCase__ ) lowercase__ : Optional[int] = { "middle_block.1.qkv.bias": { "key": "mid_block.attentions.0.key.bias", "query": "mid_block.attentions.0.query.bias", "value": "mid_block.attentions.0.value.bias", }, "middle_block.1.qkv.weight": { "key": "mid_block.attentions.0.key.weight", "query": "mid_block.attentions.0.query.weight", "value": "mid_block.attentions.0.value.weight", }, } assign_to_checkpoint( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , attention_paths_to_split=lowerCamelCase__ , config=lowerCamelCase__ ) for i in range(lowerCamelCase__ ): lowercase__ : List[Any] = i // (config["num_res_blocks"] + 1) lowercase__ : Optional[int] = i % (config["num_res_blocks"] + 1) lowercase__ : List[Any] = [shave_segments(lowerCamelCase__ , 2 ) for name in output_blocks[i]] lowercase__ : Optional[Any] = {} for layer in output_block_layers: lowercase__ , lowercase__ : str = layer.split("." )[0], shave_segments(lowerCamelCase__ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCamelCase__ ) else: lowercase__ : Tuple = [layer_name] if len(lowerCamelCase__ ) > 1: lowercase__ : Dict = [key for key in output_blocks[i] if F"""output_blocks.{i}.0""" in key] lowercase__ : Dict = [key for key in output_blocks[i] if F"""output_blocks.{i}.1""" in key] lowercase__ : Optional[Any] = renew_resnet_paths(lowerCamelCase__ ) lowercase__ : Optional[Any] = renew_resnet_paths(lowerCamelCase__ ) lowercase__ : Tuple = {"old": F"""output_blocks.{i}.0""", "new": F"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , config=lowerCamelCase__ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): lowercase__ : List[str] = list(output_block_list.values() ).index(["conv.weight", "conv.bias"] ) lowercase__ : Tuple = checkpoint[ F"""output_blocks.{i}.{index}.conv.weight""" ] lowercase__ : Optional[Any] = checkpoint[ F"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowerCamelCase__ ) == 2: lowercase__ : int = [] if len(lowerCamelCase__ ): lowercase__ : Tuple = renew_attention_paths(lowerCamelCase__ ) lowercase__ : str = { "old": F"""output_blocks.{i}.1""", "new": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } lowercase__ : Union[str, Any] = { F"""output_blocks.{i}.1.qkv.bias""": { "key": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", "query": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", "value": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, F"""output_blocks.{i}.1.qkv.weight""": { "key": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", "query": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", "value": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("qkv" in key for key in attentions ) else None , config=lowerCamelCase__ , ) else: lowercase__ : int = renew_resnet_paths(lowerCamelCase__ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: lowercase__ : List[Any] = ".".join(["output_blocks", str(lowerCamelCase__ ), path["old"]] ) lowercase__ : Any = ".".join(["up_blocks", str(lowerCamelCase__ ), "resnets", str(lowerCamelCase__ ), path["new"]] ) lowercase__ : List[Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = torch.load(args.checkpoint_path) with open(args.config_file) as f: lowerCAmelCase__ = json.loads(f.read()) lowerCAmelCase__ = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] lowerCAmelCase__ = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: lowerCAmelCase__ = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) lowerCAmelCase__ = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) lowerCAmelCase__ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
121
1
"""simple docstring""" from maths.prime_check import is_prime def UpperCAmelCase__ ( lowerCAmelCase__ :Any ) -> int: '''simple docstring''' if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowercase = f'Input value of [number={number}] must be an integer' raise TypeError(__UpperCAmelCase ) if is_prime(__UpperCAmelCase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
197
'''simple docstring''' import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' snake_case_ = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''decoder.output_projection.weight''', '''_float_tensor''', '''encoder.embed_positions._float_tensor''', '''decoder.embed_positions._float_tensor''', ] for k in ignore_keys: state_dict.pop(__UpperCAmelCase, __UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' snake_case_ = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: snake_case_ = s_dict.pop(__UpperCAmelCase ) elif "subsample" in key: snake_case_ = s_dict.pop(__UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' snake_case_ ,snake_case_ = emb.weight.shape snake_case_ = nn.Linear(__UpperCAmelCase, __UpperCAmelCase, bias=__UpperCAmelCase ) snake_case_ = emb.weight.data return lin_layer def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Dict: '''simple docstring''' snake_case_ = torch.load(__UpperCAmelCase, map_location='''cpu''' ) snake_case_ = mam_aaa['''args'''] snake_case_ = mam_aaa['''model'''] snake_case_ = state_dict['''decoder.output_projection.weight'''] remove_ignore_keys_(__UpperCAmelCase ) rename_keys(__UpperCAmelCase ) snake_case_ = state_dict['''decoder.embed_tokens.weight'''].shape[0] snake_case_ = args.share_decoder_input_output_embed snake_case_ = [int(__UpperCAmelCase ) for i in args.conv_kernel_sizes.split(''',''' )] snake_case_ = SpeechaTextConfig( vocab_size=__UpperCAmelCase, max_source_positions=args.max_source_positions, max_target_positions=args.max_target_positions, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, encoder_attention_heads=args.encoder_attention_heads, decoder_attention_heads=args.decoder_attention_heads, encoder_ffn_dim=args.encoder_ffn_embed_dim, decoder_ffn_dim=args.decoder_ffn_embed_dim, d_model=args.encoder_embed_dim, dropout=args.dropout, attention_dropout=args.attention_dropout, activation_dropout=args.activation_dropout, activation_function='''relu''', num_conv_layers=len(__UpperCAmelCase ), conv_channels=args.conv_channels, conv_kernel_sizes=__UpperCAmelCase, input_feat_per_channel=args.input_feat_per_channel, input_channels=args.input_channels, tie_word_embeddings=__UpperCAmelCase, num_beams=5, max_length=200, use_cache=__UpperCAmelCase, decoder_start_token_id=2, early_stopping=__UpperCAmelCase, ) snake_case_ = SpeechaTextForConditionalGeneration(__UpperCAmelCase ) snake_case_ ,snake_case_ = model.model.load_state_dict(__UpperCAmelCase, strict=__UpperCAmelCase ) if len(__UpperCAmelCase ) > 0 and not set(__UpperCAmelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' F" but all the following weights are missing {missing}" ) if tie_embeds: snake_case_ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ = lm_head_weights model.save_pretrained(__UpperCAmelCase ) if __name__ == "__main__": a : Any = argparse.ArgumentParser() # Required parameters parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a : List[Any] = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
56
0
from collections import deque from .hash_table import HashTable class lowerCamelCase_ ( lowercase__ ): '''simple docstring''' def __init__( self : Tuple , *_lowerCAmelCase : int , **_lowerCAmelCase : Tuple ): super().__init__(*_UpperCamelCase , **_UpperCamelCase ) def lowerCAmelCase_ ( self : Any , _lowerCAmelCase : str , _lowerCAmelCase : Optional[int] ): SCREAMING_SNAKE_CASE_ = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.values[key] def lowerCAmelCase_ ( self : Tuple ): return ( sum(self.charge_factor - len(_UpperCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def lowerCAmelCase_ ( self : List[Any] , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(_UpperCamelCase ) == 0 ): return key return super()._collision_resolution(_UpperCamelCase , _UpperCamelCase )
358
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "" lowercase_ = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self : Optional[int] , _lowerCAmelCase : Optional[DatasetInfo] = None , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : int , ): super().__init__(self , **_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = repo_info SCREAMING_SNAKE_CASE_ = token SCREAMING_SNAKE_CASE_ = None def lowerCAmelCase_ ( self : Tuple ): if self.dir_cache is None: SCREAMING_SNAKE_CASE_ = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE_ = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(_lowerCAmelCase ): {'name': str(_lowerCAmelCase ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowerCAmelCase_ ( self : Optional[int] , _lowerCAmelCase : str , _lowerCAmelCase : str = "rb" , **_lowerCAmelCase : Optional[Any] , ): if not isinstance(self.repo_info , _lowerCAmelCase ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) SCREAMING_SNAKE_CASE_ = hf_hub_url(self.repo_info.id , _lowerCAmelCase , revision=self.repo_info.sha ) return fsspec.open( _lowerCAmelCase , mode=_lowerCAmelCase , headers=get_authentication_headers_for_url(_lowerCAmelCase , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def lowerCAmelCase_ ( self : List[Any] , _lowerCAmelCase : Any , **_lowerCAmelCase : Dict ): self._get_dirs() SCREAMING_SNAKE_CASE_ = self._strip_protocol(_lowerCAmelCase ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(_lowerCAmelCase ) def lowerCAmelCase_ ( self : Optional[Any] , _lowerCAmelCase : Any , _lowerCAmelCase : Any=False , **_lowerCAmelCase : str ): self._get_dirs() SCREAMING_SNAKE_CASE_ = PurePosixPath(path.strip('/' ) ) SCREAMING_SNAKE_CASE_ = {} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE_ = PurePosixPath(p.strip('/' ) ) SCREAMING_SNAKE_CASE_ = p.parent if root == path: SCREAMING_SNAKE_CASE_ = f SCREAMING_SNAKE_CASE_ = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
210
0
'''simple docstring''' import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : """simple docstring""" def __init__( self : str , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Tuple=1_3 , lowerCAmelCase__ : str=[3_0, 3_0] , lowerCAmelCase__ : str=2 , lowerCAmelCase__ : Optional[Any]=3 , lowerCAmelCase__ : Any=True , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : Union[str, Any]=3_2 , lowerCAmelCase__ : Optional[Any]=5 , lowerCAmelCase__ : Union[str, Any]=4 , lowerCAmelCase__ : int=3_7 , lowerCAmelCase__ : Union[str, Any]="gelu" , lowerCAmelCase__ : List[Any]=0.1 , lowerCAmelCase__ : Optional[int]=0.1 , lowerCAmelCase__ : List[Any]=1_0 , lowerCAmelCase__ : Any=0.02 , lowerCAmelCase__ : List[Any]=3 , lowerCAmelCase__ : int=None , lowerCAmelCase__ : Dict=8 , lowerCAmelCase__ : List[Any]=1_0 , ) -> List[str]: """simple docstring""" _UpperCAmelCase : Optional[int] = parent _UpperCAmelCase : List[str] = batch_size _UpperCAmelCase : Tuple = image_size _UpperCAmelCase : int = patch_size _UpperCAmelCase : Union[str, Any] = num_channels _UpperCAmelCase : Any = is_training _UpperCAmelCase : Union[str, Any] = use_labels _UpperCAmelCase : List[Any] = hidden_size _UpperCAmelCase : Tuple = num_hidden_layers _UpperCAmelCase : Tuple = num_attention_heads _UpperCAmelCase : Union[str, Any] = intermediate_size _UpperCAmelCase : Union[str, Any] = hidden_act _UpperCAmelCase : int = hidden_dropout_prob _UpperCAmelCase : Dict = attention_probs_dropout_prob _UpperCAmelCase : Optional[int] = type_sequence_label_size _UpperCAmelCase : List[str] = initializer_range _UpperCAmelCase : Dict = num_labels _UpperCAmelCase : Tuple = scope _UpperCAmelCase : Optional[int] = n_targets _UpperCAmelCase : Any = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens _UpperCAmelCase : str = (image_size[1] // patch_size) * (image_size[0] // patch_size) _UpperCAmelCase : Dict = num_patches + 1 + self.num_detection_tokens def _lowerCAmelCase ( self : str ) -> List[str]: """simple docstring""" _UpperCAmelCase : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) _UpperCAmelCase : Tuple = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) _UpperCAmelCase : List[Any] = [] for i in range(self.batch_size ): _UpperCAmelCase : Optional[Any] = {} _UpperCAmelCase : str = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=__lowercase ) _UpperCAmelCase : Optional[Any] = torch.rand(self.n_targets , 4 , device=__lowercase ) labels.append(__lowercase ) _UpperCAmelCase : Union[str, Any] = self.get_config() return config, pixel_values, labels def _lowerCAmelCase ( self : int ) -> List[Any]: """simple docstring""" return YolosConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowercase , initializer_range=self.initializer_range , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def _lowerCAmelCase ( self : Optional[int] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : Optional[Any] = YolosModel(config=__lowercase ) model.to(__lowercase ) model.eval() _UpperCAmelCase : Union[str, Any] = model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int ) -> int: """simple docstring""" _UpperCAmelCase : str = YolosForObjectDetection(__lowercase ) model.to(__lowercase ) model.eval() _UpperCAmelCase : str = model(pixel_values=__lowercase ) _UpperCAmelCase : Optional[int] = model(__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) _UpperCAmelCase : Dict = model(pixel_values=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def _lowerCAmelCase ( self : Any ) -> Any: """simple docstring""" _UpperCAmelCase : int = self.prepare_config_and_inputs() _UpperCAmelCase : Union[str, Any] = config_and_inputs _UpperCAmelCase : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] = (YolosModel, YolosForObjectDetection) if is_torch_available() else () UpperCamelCase_ : Tuple = ( {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {} ) UpperCamelCase_ : Optional[Any] = False UpperCamelCase_ : Optional[Any] = False UpperCamelCase_ : Union[str, Any] = False UpperCamelCase_ : List[str] = False def _lowerCAmelCase ( self : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple=False ) -> Tuple: """simple docstring""" _UpperCAmelCase : Optional[Any] = super()._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": _UpperCAmelCase : Dict = [] for i in range(self.model_tester.batch_size ): _UpperCAmelCase : Union[str, Any] = {} _UpperCAmelCase : Tuple = torch.ones( size=(self.model_tester.n_targets,) , device=__lowercase , dtype=torch.long ) _UpperCAmelCase : str = torch.ones( self.model_tester.n_targets , 4 , device=__lowercase , dtype=torch.float ) labels.append(__lowercase ) _UpperCAmelCase : Union[str, Any] = labels return inputs_dict def _lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase : Any = YolosModelTester(self ) _UpperCAmelCase : List[Any] = ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=3_7 ) def _lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" pass def _lowerCAmelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : Tuple = model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def _lowerCAmelCase ( self : int ) -> Optional[int]: """simple docstring""" _UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : str = model_class(__lowercase ) _UpperCAmelCase : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase : int = [*signature.parameters.keys()] _UpperCAmelCase : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase ) def _lowerCAmelCase ( self : Optional[int] ) -> Any: """simple docstring""" _UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def _lowerCAmelCase ( self : Tuple ) -> str: """simple docstring""" _UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase : str = True # in YOLOS, the seq_len is different _UpperCAmelCase : List[str] = self.model_tester.expected_seq_len for model_class in self.all_model_classes: _UpperCAmelCase : Dict = True _UpperCAmelCase : List[Any] = False _UpperCAmelCase : Optional[Any] = True _UpperCAmelCase : List[Any] = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): _UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(__lowercase , __lowercase ) ) _UpperCAmelCase : List[str] = outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _UpperCAmelCase : Optional[Any] = True _UpperCAmelCase : List[str] = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): _UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(__lowercase , __lowercase ) ) _UpperCAmelCase : List[str] = outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _UpperCAmelCase : int = len(__lowercase ) # Check attention is always last and order is fine _UpperCAmelCase : Any = True _UpperCAmelCase : List[Any] = True _UpperCAmelCase : Dict = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): _UpperCAmelCase : int = model(**self._prepare_for_class(__lowercase , __lowercase ) ) _UpperCAmelCase : List[Any] = 1 self.assertEqual(out_len + added_hidden_states , len(__lowercase ) ) _UpperCAmelCase : Union[str, Any] = outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def _lowerCAmelCase ( self : str ) -> Optional[Any]: """simple docstring""" def check_hidden_states_output(lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] ): _UpperCAmelCase : List[Any] = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): _UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(__lowercase , __lowercase ) ) _UpperCAmelCase : Any = outputs.hidden_states _UpperCAmelCase : Any = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__lowercase ) , __lowercase ) # YOLOS has a different seq_length _UpperCAmelCase : List[str] = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : Tuple = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase : Any = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def _lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" _UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*__lowercase ) @slow def _lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase : Any = YolosModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def __UpperCAmelCase ( ): _UpperCAmelCase : Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : List[str] ) -> List[str]: """simple docstring""" return AutoImageProcessor.from_pretrained("hustvl/yolos-small" ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ) -> Any: """simple docstring""" _UpperCAmelCase : List[str] = YolosForObjectDetection.from_pretrained("hustvl/yolos-small" ).to(__lowercase ) _UpperCAmelCase : Dict = self.default_image_processor _UpperCAmelCase : Optional[int] = prepare_img() _UpperCAmelCase : Any = image_processor(images=__lowercase , return_tensors="pt" ).to(__lowercase ) # forward pass with torch.no_grad(): _UpperCAmelCase : Optional[int] = model(inputs.pixel_values ) # verify outputs _UpperCAmelCase : str = torch.Size((1, 1_0_0, 9_2) ) self.assertEqual(outputs.logits.shape , __lowercase ) _UpperCAmelCase : int = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] , device=__lowercase , ) _UpperCAmelCase : Any = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] , device=__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , __lowercase , atol=1e-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowercase , atol=1e-4 ) ) # verify postprocessing _UpperCAmelCase : Tuple = image_processor.post_process_object_detection( __lowercase , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] _UpperCAmelCase : Optional[int] = torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861] ).to(__lowercase ) _UpperCAmelCase : Optional[int] = [7_5, 7_5, 1_7, 6_3, 1_7] _UpperCAmelCase : int = torch.tensor([3_3_5.0_6_0_9, 79.3848, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5] ).to(__lowercase ) self.assertEqual(len(results["scores"] ) , 5 ) self.assertTrue(torch.allclose(results["scores"] , __lowercase , atol=1e-4 ) ) self.assertSequenceEqual(results["labels"].tolist() , __lowercase ) self.assertTrue(torch.allclose(results["boxes"][0, :] , __lowercase ) )
145
import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :List[Any] = AlbertConfig.from_json_file(SCREAMING_SNAKE_CASE ) print(f"""Building PyTorch model from configuration: {config}""" ) __UpperCamelCase :List[str] = AlbertForPreTraining(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_albert(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) 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( '''--albert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained ALBERT 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.''' ) __lowercase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
43
0
"""simple docstring""" from __future__ import annotations __UpperCAmelCase : Any = "Muhammad Umer Farooq" __UpperCAmelCase : List[str] = "MIT" __UpperCAmelCase : Any = "1.0.0" __UpperCAmelCase : Optional[int] = "Muhammad Umer Farooq" __UpperCAmelCase : Optional[Any] = "contact@muhammadumerfarooq.me" __UpperCAmelCase : str = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class UpperCAmelCase_ ( a__): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__() UpperCamelCase : list[str] = [] UpperCamelCase : str = domain def _lowercase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: UpperCamelCase : List[str] = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def a ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" return ".".join(get_sub_domain_name(_lowerCamelCase ).split('''.''' )[-2:] ) def a ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" return parse.urlparse(_lowerCamelCase ).netloc def a ( SCREAMING_SNAKE_CASE_ : str = "https://github.com" ): """simple docstring""" UpperCamelCase : Optional[int] = get_domain_name(_lowerCamelCase ) # Initialize the parser UpperCamelCase : List[str] = Parser(_lowerCamelCase ) try: # Open URL UpperCamelCase : Optional[Any] = requests.get(_lowerCamelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through UpperCamelCase : str = set() for link in parser.urls: # open URL. # read = requests.get(link) try: UpperCamelCase : Optional[Any] = requests.get(_lowerCamelCase ) # Get the valid email. UpperCamelCase : Any = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(_lowerCamelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_lowerCamelCase ) if __name__ == "__main__": __UpperCAmelCase : Dict = emails_from_url("https://github.com") print(f'''{len(emails)} emails found:''') print("\n".join(sorted(emails)))
370
# Copyright 2023 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. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase : Union[str, Any] = { "configuration_mgp_str": ["MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP", "MgpstrConfig"], "processing_mgp_str": ["MgpstrProcessor"], "tokenization_mgp_str": ["MgpstrTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase : Union[str, Any] = [ "MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST", "MgpstrModel", "MgpstrPreTrainedModel", "MgpstrForSceneTextRecognition", ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys __UpperCAmelCase : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
315
0
"""simple docstring""" from math import ceil def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any] ) -> int: _lowerCAmelCase : Dict = list(range(0 ,_lowerCamelCase ) ) _lowerCAmelCase : Tuple = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check _lowerCAmelCase : Union[str, Any] = [] for i in device_map_blocks: if device_map_blocks.count(_lowerCamelCase ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(_lowerCamelCase ) # Missing blocks _lowerCAmelCase : int = [i for i in blocks if i not in device_map_blocks] _lowerCAmelCase : List[Any] = [i for i in device_map_blocks if i not in blocks] if len(_lowerCamelCase ) != 0: raise ValueError( """Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device.""" """ These attention blocks were specified more than once: """ + str(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( """There are attention blocks for this model that are not specified in the device_map. Add these attention """ """blocks to a device on the device_map: """ + str(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : Tuple ) -> str: _lowerCAmelCase : Optional[Any] = list(range(_lowerCamelCase ) ) _lowerCAmelCase : Optional[Any] = int(ceil(n_layers / len(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[int] = [layers[i : i + n_blocks] for i in range(0 ,_lowerCamelCase ,_lowerCamelCase )] return dict(zip(_lowerCamelCase ,_lowerCamelCase ) )
44
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False')) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env') @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_5_0, 'eval_accuracy': 0.7, 'eval_loss': 0.6}, }, { 'framework': 'pytorch', 'script': 'run_ddp.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_0_0, 'eval_accuracy': 0.7, 'eval_loss': 0.6}, }, { 'framework': 'tensorflow', 'script': 'run_tf_dist.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_0_0, 'eval_accuracy': 0.6, 'eval_loss': 0.7}, }, ]) class lowerCamelCase__ ( unittest.TestCase): '''simple docstring''' def _lowerCamelCase ( self :List[Any] ) -> Any: if self.framework == "pytorch": subprocess.run( f'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding="utf-8" , check=a , ) assert hasattr(self , "env" ) def _lowerCamelCase ( self :Any , a :Optional[Any] ) -> Dict: __UpperCamelCase : str = f'{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}' # distributed data settings __UpperCamelCase : Optional[int] = {"smdistributed": {"dataparallel": {"enabled": True}}} if self.script != "run_ddp.py" else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=a , instance_count=a , instance_type=self.instance_type , debugger_hook_config=a , hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=a , py_version="py36" , ) def _lowerCamelCase ( self :Dict , a :Dict ) -> Optional[int]: TrainingJobAnalytics(a ).export_csv(f'{self.env.test_path}/{job_name}_metrics.csv' ) @parameterized.expand([(2,)] ) def _lowerCamelCase ( self :Dict , a :Tuple ) -> List[Any]: # create estimator __UpperCamelCase : int = self.create_estimator(a ) # run training estimator.fit() # result dataframe __UpperCamelCase : Optional[int] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __UpperCamelCase : Optional[Any] = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) __UpperCamelCase : Tuple = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __UpperCamelCase : int = ( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy ) assert all(t <= self.results["eval_loss"] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'{estimator.latest_training_job.name}.json' , "w" ) as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss} , a )
232
0
'''simple docstring''' from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig 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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ : def __init__( self : str , __a : Optional[int] , __a : str=3 , __a : Optional[int]=32 , __a : Optional[Any]=3 , __a : Optional[int]=10 , __a : List[Any]=[10, 20, 30, 40] , __a : Dict=[1, 1, 2, 1] , __a : Tuple=True , __a : Union[str, Any]=True , __a : Dict="relu" , __a : Any=3 , __a : str=None , ) -> int: '''simple docstring''' __snake_case : str = parent __snake_case : Union[str, Any] = batch_size __snake_case : List[str] = image_size __snake_case : Tuple = num_channels __snake_case : Any = embeddings_size __snake_case : List[Any] = hidden_sizes __snake_case : str = depths __snake_case : int = is_training __snake_case : List[str] = use_labels __snake_case : Tuple = hidden_act __snake_case : Any = num_labels __snake_case : List[str] = scope __snake_case : Dict = len(__a ) def A_ ( self : int ) -> Optional[int]: '''simple docstring''' __snake_case : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : str = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Tuple = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[Any] ) -> Dict: '''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 , ) def A_ ( self : Optional[Any] , __a : Any , __a : Union[str, Any] , __a : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = TFRegNetModel(config=__a ) __snake_case : Union[str, Any] = model(__a , training=__a ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def A_ ( self : List[str] , __a : Dict , __a : Union[str, Any] , __a : Optional[Any] ) -> Tuple: '''simple docstring''' __snake_case : List[str] = self.num_labels __snake_case : List[Any] = TFRegNetForImageClassification(__a ) __snake_case : Optional[int] = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : List[Any] = self.prepare_config_and_inputs() __snake_case : Any = config_and_inputs __snake_case : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () A__ = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) A__ = False A__ = False A__ = False A__ = False A__ = False def A_ ( self : List[str] ) -> Tuple: '''simple docstring''' __snake_case : str = TFRegNetModelTester(self ) __snake_case : Optional[Any] = ConfigTester(self , config_class=__a , has_text_modality=__a ) def A_ ( self : Optional[int] ) -> Tuple: '''simple docstring''' return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def A_ ( self : List[Any] ) -> 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.' , ) @slow def A_ ( self : List[str] ) -> Any: '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def A_ ( self : str ) -> str: '''simple docstring''' pass def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Tuple = model_class(__a ) __snake_case : List[str] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Optional[int] = [*signature.parameters.keys()] __snake_case : Any = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' def check_hidden_states_output(__a : List[str] , __a : List[Any] , __a : Optional[Any] ): __snake_case : List[Any] = model_class(__a ) __snake_case : int = model(**self._prepare_for_class(__a , __a ) , training=__a ) __snake_case : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : List[Any] = self.model_tester.num_stages self.assertEqual(len(__a ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : Optional[int] = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: __snake_case : List[str] = layer_type __snake_case : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : str = True check_hidden_states_output(__a , __a , __a ) def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(__a : Optional[int] , __a : Tuple , __a : Union[str, Any] , __a : List[Any]={} ): __snake_case : Optional[Any] = model(__a , return_dict=__a , **__a ) __snake_case : Tuple = model(__a , return_dict=__a , **__a ).to_tuple() def recursive_check(__a : Tuple , __a : Optional[int] ): if isinstance(__a , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__a , __a ): recursive_check(__a , __a ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(__a , __a ) ) , msg=( 'Tuple and dict output are not equal. Difference:' f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(__a , __a ) for model_class in self.all_model_classes: __snake_case : List[str] = model_class(__a ) __snake_case : List[Any] = self._prepare_for_class(__a , __a ) __snake_case : str = self._prepare_for_class(__a , __a ) check_equivalence(__a , __a , __a ) __snake_case : List[str] = self._prepare_for_class(__a , __a , return_labels=__a ) __snake_case : Tuple = self._prepare_for_class(__a , __a , return_labels=__a ) check_equivalence(__a , __a , __a ) __snake_case : Union[str, Any] = self._prepare_for_class(__a , __a ) __snake_case : Union[str, Any] = self._prepare_for_class(__a , __a ) check_equivalence(__a , __a , __a , {'output_hidden_states': True} ) __snake_case : Optional[Any] = self._prepare_for_class(__a , __a , return_labels=__a ) __snake_case : Any = self._prepare_for_class(__a , __a , return_labels=__a ) check_equivalence(__a , __a , __a , {'output_hidden_states': True} ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = TFRegNetModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def a_ ( ) -> Optional[int]: __snake_case : Any = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def A_ ( self : List[Any] ) -> str: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def A_ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : List[str] = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __snake_case : str = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : str = image_processor(images=__a , return_tensors='tf' ) # forward pass __snake_case : Optional[int] = model(**__a , training=__a ) # verify the logits __snake_case : List[str] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __snake_case : List[str] = tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , __a , atol=1e-4 )
355
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
0
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :Dict , __magic_name__ :Dict ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): a = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = """sgugger/tiny-distilbert-classification""" a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , only_pretrain_model=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , torchscript=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def lowerCamelCase__ ( self :str ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , fpaa=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self :str ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = AutoConfig.from_pretrained(__magic_name__ ) # set architectures equal to `None` a = None a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ , configs=[config] ) a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=__magic_name__ , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = AutoConfig.from_pretrained(__magic_name__ ) a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ , configs=[config] ) a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = """sshleifer/tinier_bart""" a = AutoConfig.from_pretrained(__magic_name__ ) a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ , configs=[config] ) a = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" a = AutoConfig.from_pretrained(__magic_name__ ) a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ , configs=[config] ) a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = """sshleifer/tinier_bart""" a = AutoConfig.from_pretrained(__magic_name__ ) a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ , configs=[config] ) a = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , save_to_csv=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__magic_name__ , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(__magic_name__ , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(__magic_name__ , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(__magic_name__ , """train_time.csv""" ) , env_info_csv_file=os.path.join(__magic_name__ , """env.csv""" ) , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) benchmark.run() self.assertTrue(Path(os.path.join(__magic_name__ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(__magic_name__ , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(__magic_name__ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(__magic_name__ , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(__magic_name__ , """env.csv""" ) ).exists() ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(__magic_name__ :Tuple ): self.assertTrue(hasattr(__magic_name__ , """sequential""" ) ) self.assertTrue(hasattr(__magic_name__ , """cumulative""" ) ) self.assertTrue(hasattr(__magic_name__ , """current""" ) ) self.assertTrue(hasattr(__magic_name__ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: a = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__magic_name__ , """log.txt""" ) , log_print=__magic_name__ , trace_memory_line_by_line=__magic_name__ , multi_process=__magic_name__ , ) a = PyTorchBenchmark(__magic_name__ ) a = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(__magic_name__ , """log.txt""" ) ).exists() )
228
def __A ( __lowerCamelCase ) -> int: a = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __A ( __lowerCamelCase = 100 ) -> int: a = 1 a = 2 for i in range(2 , max_n + 1 ): a = pre_numerator a = 2 * i // 3 if i % 3 == 0 else 1 a = cur_numerator a = e_cont * pre_numerator + temp return sum_digits(__lowerCamelCase ) if __name__ == "__main__": print(F'{solution() = }')
228
1
from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: int = ["sentencepiece"] def __init__( self: Dict , *__lowerCamelCase: Optional[int] , **__lowerCamelCase: Union[str, Any] ) -> List[str]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: str = ["sentencepiece"] def __init__( self: int , *__lowerCamelCase: Optional[int] , **__lowerCamelCase: Tuple ) -> List[str]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: int = ["sentencepiece"] def __init__( self: Union[str, Any] , *__lowerCamelCase: List[str] , **__lowerCamelCase: Any ) -> Any: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Any = ["sentencepiece"] def __init__( self: Union[str, Any] , *__lowerCamelCase: Any , **__lowerCamelCase: Optional[Any] ) -> int: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Union[str, Any] = ["sentencepiece"] def __init__( self: Dict , *__lowerCamelCase: List[str] , **__lowerCamelCase: Optional[Any] ) -> Union[str, Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Optional[Any] = ["sentencepiece"] def __init__( self: Tuple , *__lowerCamelCase: Optional[Any] , **__lowerCamelCase: Tuple ) -> Optional[int]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: List[str] = ["sentencepiece"] def __init__( self: Any , *__lowerCamelCase: Optional[Any] , **__lowerCamelCase: Union[str, Any] ) -> Dict: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Tuple = ["sentencepiece"] def __init__( self: int , *__lowerCamelCase: str , **__lowerCamelCase: Any ) -> Any: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: str = ["sentencepiece"] def __init__( self: Tuple , *__lowerCamelCase: str , **__lowerCamelCase: Tuple ) -> List[str]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Dict = ["sentencepiece"] def __init__( self: List[str] , *__lowerCamelCase: Any , **__lowerCamelCase: int ) -> List[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Union[str, Any] = ["sentencepiece"] def __init__( self: Optional[Any] , *__lowerCamelCase: Union[str, Any] , **__lowerCamelCase: List[Any] ) -> str: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: str = ["sentencepiece"] def __init__( self: int , *__lowerCamelCase: List[Any] , **__lowerCamelCase: List[Any] ) -> List[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: List[str] = ["sentencepiece"] def __init__( self: Dict , *__lowerCamelCase: List[str] , **__lowerCamelCase: List[str] ) -> Optional[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: int = ["sentencepiece"] def __init__( self: Optional[Any] , *__lowerCamelCase: Optional[int] , **__lowerCamelCase: Tuple ) -> Optional[int]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Union[str, Any] = ["sentencepiece"] def __init__( self: Optional[Any] , *__lowerCamelCase: Optional[Any] , **__lowerCamelCase: Tuple ) -> Optional[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Union[str, Any] = ["sentencepiece"] def __init__( self: str , *__lowerCamelCase: Dict , **__lowerCamelCase: List[Any] ) -> Union[str, Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Tuple = ["sentencepiece"] def __init__( self: Optional[Any] , *__lowerCamelCase: Union[str, Any] , **__lowerCamelCase: Tuple ) -> Tuple: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Any = ["sentencepiece"] def __init__( self: List[str] , *__lowerCamelCase: int , **__lowerCamelCase: Dict ) -> str: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: List[str] = ["sentencepiece"] def __init__( self: Tuple , *__lowerCamelCase: List[Any] , **__lowerCamelCase: Dict ) -> int: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: List[str] = ["sentencepiece"] def __init__( self: Any , *__lowerCamelCase: List[Any] , **__lowerCamelCase: int ) -> Tuple: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Union[str, Any] = ["sentencepiece"] def __init__( self: Optional[int] , *__lowerCamelCase: Union[str, Any] , **__lowerCamelCase: List[str] ) -> Union[str, Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Union[str, Any] = ["sentencepiece"] def __init__( self: Union[str, Any] , *__lowerCamelCase: Dict , **__lowerCamelCase: Optional[int] ) -> List[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Optional[int] = ["sentencepiece"] def __init__( self: str , *__lowerCamelCase: str , **__lowerCamelCase: Optional[int] ) -> Union[str, Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: str = ["sentencepiece"] def __init__( self: Any , *__lowerCamelCase: Union[str, Any] , **__lowerCamelCase: Optional[Any] ) -> List[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Tuple = ["sentencepiece"] def __init__( self: int , *__lowerCamelCase: List[str] , **__lowerCamelCase: List[str] ) -> Any: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Tuple = ["sentencepiece"] def __init__( self: Tuple , *__lowerCamelCase: Optional[Any] , **__lowerCamelCase: Tuple ) -> List[str]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: int = ["sentencepiece"] def __init__( self: List[str] , *__lowerCamelCase: Tuple , **__lowerCamelCase: str ) -> str: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: List[str] = ["sentencepiece"] def __init__( self: Union[str, Any] , *__lowerCamelCase: int , **__lowerCamelCase: Dict ) -> str: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: Optional[int] = ["sentencepiece"] def __init__( self: List[Any] , *__lowerCamelCase: Tuple , **__lowerCamelCase: Optional[Any] ) -> List[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: int = ["sentencepiece"] def __init__( self: List[str] , *__lowerCamelCase: Any , **__lowerCamelCase: Optional[Any] ) -> Optional[Any]: requires_backends(self , ["sentencepiece"] ) class _snake_case ( metaclass=_lowercase ): lowerCamelCase__: List[Any] = ["sentencepiece"] def __init__( self: int , *__lowerCamelCase: Union[str, Any] , **__lowerCamelCase: Optional[int] ) -> Any: requires_backends(self , ["sentencepiece"] )
342
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class _snake_case ( _lowercase ): lowerCamelCase__: Dict = "roc_bert" def __init__( self: int , __lowerCamelCase: Union[str, Any]=3_05_22 , __lowerCamelCase: int=7_68 , __lowerCamelCase: Any=12 , __lowerCamelCase: int=12 , __lowerCamelCase: Union[str, Any]=30_72 , __lowerCamelCase: Union[str, Any]="gelu" , __lowerCamelCase: Optional[int]=0.1 , __lowerCamelCase: str=0.1 , __lowerCamelCase: Any=5_12 , __lowerCamelCase: Union[str, Any]=2 , __lowerCamelCase: str=0.02 , __lowerCamelCase: int=1e-12 , __lowerCamelCase: str=True , __lowerCamelCase: int=0 , __lowerCamelCase: List[str]="absolute" , __lowerCamelCase: List[Any]=None , __lowerCamelCase: Optional[int]=True , __lowerCamelCase: List[str]=True , __lowerCamelCase: Dict=7_68 , __lowerCamelCase: Optional[int]=9_10 , __lowerCamelCase: Union[str, Any]=5_12 , __lowerCamelCase: int=2_48_58 , __lowerCamelCase: Optional[int]=True , **__lowerCamelCase: Any , ) -> List[Any]: __UpperCAmelCase : str = vocab_size __UpperCAmelCase : Dict = max_position_embeddings __UpperCAmelCase : Optional[Any] = hidden_size __UpperCAmelCase : Optional[int] = num_hidden_layers __UpperCAmelCase : Union[str, Any] = num_attention_heads __UpperCAmelCase : List[str] = intermediate_size __UpperCAmelCase : List[Any] = hidden_act __UpperCAmelCase : List[str] = hidden_dropout_prob __UpperCAmelCase : Optional[int] = attention_probs_dropout_prob __UpperCAmelCase : Union[str, Any] = initializer_range __UpperCAmelCase : Optional[Any] = type_vocab_size __UpperCAmelCase : List[Any] = layer_norm_eps __UpperCAmelCase : Optional[int] = use_cache __UpperCAmelCase : Optional[Any] = enable_pronunciation __UpperCAmelCase : Any = enable_shape __UpperCAmelCase : Union[str, Any] = pronunciation_embed_dim __UpperCAmelCase : Optional[Any] = pronunciation_vocab_size __UpperCAmelCase : Optional[Any] = shape_embed_dim __UpperCAmelCase : List[Any] = shape_vocab_size __UpperCAmelCase : int = concat_input __UpperCAmelCase : int = position_embedding_type __UpperCAmelCase : Optional[int] = classifier_dropout super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase )
342
1