code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import copy import re class lowerCAmelCase_ : """simple docstring""" _snake_case : str = '''hp''' _snake_case : List[Any] = {} _snake_case : List[Any] = None @classmethod def __a ( cls :List[Any] , lowerCamelCase__ :List[str] , lowerCamelCase__ :Optional[Any] ): UpperCamelCase__ :int = prefix UpperCamelCase__ :Optional[Any] = defaults cls.build_naming_info() @staticmethod def __a ( lowerCamelCase__ :Any , lowerCamelCase__ :List[Any] ): if len(A_ ) == 0: return "" UpperCamelCase__ :List[str] = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: \'{word}\' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(A_ ) + 1 ): UpperCamelCase__ :Any = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCamelCase__ :Any = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(lowerCamelCase__ :Optional[Any] ): UpperCamelCase__ :Optional[Any] = """""" while integer != 0: UpperCamelCase__ :Any = chr(ord("""A""" ) + integer % 10 ) + s integer //= 10 return s UpperCamelCase__ :Optional[int] = 0 while True: UpperCamelCase__ :List[Any] = word + """#""" + int_to_alphabetic(A_ ) if sword in info["reverse_short_word"]: continue else: UpperCamelCase__ :int = sword break UpperCamelCase__ :Any = short_word UpperCamelCase__ :List[str] = word return short_word @staticmethod def __a ( lowerCamelCase__ :List[Any] , lowerCamelCase__ :Union[str, Any] ): UpperCamelCase__ :Any = param_name.split("""_""" ) UpperCamelCase__ :Optional[int] = [TrialShortNamer.shortname_for_word(A_ , A_ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCamelCase__ :Tuple = ["""""", """_"""] for separator in separators: UpperCamelCase__ :Any = separator.join(A_ ) if shortname not in info["reverse_short_param"]: UpperCamelCase__ :Any = shortname UpperCamelCase__ :Any = param_name return shortname return param_name @staticmethod def __a ( lowerCamelCase__ :List[Any] , lowerCamelCase__ :Any ): UpperCamelCase__ :Optional[Any] = TrialShortNamer.shortname_for_key(A_ , A_ ) UpperCamelCase__ :List[str] = short_name UpperCamelCase__ :Union[str, Any] = param_name @classmethod def __a ( cls :Dict ): if cls.NAMING_INFO is not None: return UpperCamelCase__ :List[str] = { """short_word""": {}, """reverse_short_word""": {}, """short_param""": {}, """reverse_short_param""": {}, } UpperCamelCase__ :Any = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(A_ , A_ ) UpperCamelCase__ :Tuple = info @classmethod def __a ( cls :List[Any] , lowerCamelCase__ :Union[str, Any] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCamelCase__ :Any = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCamelCase__ :str = cls.NAMING_INFO["""short_param"""][k] if isinstance(A_ , A_ ): UpperCamelCase__ :Optional[Any] = 1 if v else 0 UpperCamelCase__ :List[str] = """""" if isinstance(A_ , (int, float) ) else """-""" UpperCamelCase__ :str = f"""{key}{sep}{v}""" name.append(A_ ) return "_".join(A_ ) @classmethod def __a ( cls :List[str] , lowerCamelCase__ :Any ): UpperCamelCase__ :str = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCamelCase__ :Optional[int] = [] else: UpperCamelCase__ :Optional[int] = repr.split("""_""" ) UpperCamelCase__ :Dict = {} for value in values: if "-" in value: UpperCamelCase__ , UpperCamelCase__ :Union[str, Any] = value.split("""-""" ) else: UpperCamelCase__ :Optional[int] = re.sub("""[0-9.]""" , """""" , A_ ) UpperCamelCase__ :List[str] = float(re.sub("""[^0-9.]""" , """""" , A_ ) ) UpperCamelCase__ :Optional[Any] = cls.NAMING_INFO["""reverse_short_param"""][p_k] UpperCamelCase__ :Union[str, Any] = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCamelCase__ :List[Any] = cls.DEFAULTS[k] return parameters
45
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def _snake_case ( ): A = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A = get_sagemaker_input() else: A = get_cluster_input() return config def _snake_case ( snake_case__ : Any=None ): if subparsers is not None: A = subparsers.add_parser('config' , description=snake_case__ ) else: A = argparse.ArgumentParser('Accelerate config command' , description=snake_case__ ) parser.add_argument( '--config_file' , default=snake_case__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=snake_case__ ) return parser def _snake_case ( snake_case__ : Tuple ): A = get_user_input() if args.config_file is not None: A = args.config_file else: if not os.path.isdir(snake_case__ ): os.makedirs(snake_case__ ) A = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(snake_case__ ) else: config.to_yaml_file(snake_case__ ) print(F'accelerate configuration saved at {config_file}' ) def _snake_case ( ): A = config_command_parser() A = parser.parse_args() config_command(snake_case__ ) if __name__ == "__main__": main()
91
0
"""simple docstring""" import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class _snake_case ( _lowercase ): def __init__( self : Union[str, Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : List[str]=13 , UpperCAmelCase : Union[str, Any]=7 , UpperCAmelCase : Dict=True , UpperCAmelCase : List[str]=True , UpperCAmelCase : str=False , UpperCAmelCase : Any=True , UpperCAmelCase : Any=99 , UpperCAmelCase : List[Any]=32 , UpperCAmelCase : int=5 , UpperCAmelCase : Tuple=4 , UpperCAmelCase : Optional[Any]=37 , UpperCAmelCase : Optional[Any]="gelu" , UpperCAmelCase : str=0.1 , UpperCAmelCase : Optional[Any]=0.1 , UpperCAmelCase : Union[str, Any]=512 , UpperCAmelCase : Any=16 , UpperCAmelCase : Dict=2 , UpperCAmelCase : str=0.0_2 , UpperCAmelCase : Union[str, Any]=3 , UpperCAmelCase : Tuple=4 , UpperCAmelCase : Any=None , ): __lowerCamelCase : List[Any] = parent __lowerCamelCase : Union[str, Any] = batch_size __lowerCamelCase : Any = seq_length __lowerCamelCase : Dict = is_training __lowerCamelCase : List[Any] = use_input_mask __lowerCamelCase : int = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Dict = hidden_size __lowerCamelCase : Optional[Any] = num_hidden_layers __lowerCamelCase : Optional[int] = num_attention_heads __lowerCamelCase : List[str] = intermediate_size __lowerCamelCase : Optional[Any] = hidden_act __lowerCamelCase : List[str] = hidden_dropout_prob __lowerCamelCase : str = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Dict = type_vocab_size __lowerCamelCase : Dict = type_sequence_label_size __lowerCamelCase : Optional[int] = initializer_range __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : Union[str, Any] = num_choices __lowerCamelCase : str = scope def lowerCamelCase__ ( self : Any ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = None if self.use_input_mask: __lowerCamelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase : Union[str, Any] = None __lowerCamelCase : str = None __lowerCamelCase : Optional[int] = None if self.use_labels: __lowerCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) __lowerCamelCase : int = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : int ): return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def lowerCamelCase__ ( self : Optional[int] , UpperCAmelCase : Dict , UpperCAmelCase : Optional[int] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : str , UpperCAmelCase : Optional[Any] ): __lowerCamelCase : Optional[Any] = DistilBertModel(config=A_ ) model.to(A_ ) model.eval() __lowerCamelCase : int = model(A_ , A_ ) __lowerCamelCase : List[str] = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : int , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[int] , UpperCAmelCase : Dict , UpperCAmelCase : int , UpperCAmelCase : List[Any] , UpperCAmelCase : int ): __lowerCamelCase : Optional[Any] = DistilBertForMaskedLM(config=A_ ) model.to(A_ ) model.eval() __lowerCamelCase : List[str] = model(A_ , attention_mask=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : Optional[Any] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Dict , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : str , UpperCAmelCase : Any ): __lowerCamelCase : int = DistilBertForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() __lowerCamelCase : Optional[Any] = model( A_ , attention_mask=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 lowerCamelCase__ ( self : int , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : int , UpperCAmelCase : List[Any] , UpperCAmelCase : Optional[Any] ): __lowerCamelCase : Optional[int] = self.num_labels __lowerCamelCase : Optional[int] = DistilBertForSequenceClassification(A_ ) model.to(A_ ) model.eval() __lowerCamelCase : Optional[int] = model(A_ , attention_mask=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : Dict , UpperCAmelCase : List[str] , UpperCAmelCase : Tuple , UpperCAmelCase : List[str] , UpperCAmelCase : str , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : List[str] ): __lowerCamelCase : str = self.num_labels __lowerCamelCase : Dict = DistilBertForTokenClassification(config=A_ ) model.to(A_ ) model.eval() __lowerCamelCase : Union[str, Any] = model(A_ , attention_mask=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase__ ( self : int , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : int , UpperCAmelCase : List[str] , UpperCAmelCase : Tuple ): __lowerCamelCase : List[Any] = self.num_choices __lowerCamelCase : List[Any] = DistilBertForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() __lowerCamelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : Union[str, Any] = model( A_ , attention_mask=A_ , labels=A_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase__ ( self : str ): __lowerCamelCase : Union[str, Any] = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Optional[Any] = config_and_inputs __lowerCamelCase : List[str] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _snake_case ( _lowercase , _lowercase , unittest.TestCase ): snake_case__ = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) snake_case__ = ( { '''feature-extraction''': DistilBertModel, '''fill-mask''': DistilBertForMaskedLM, '''question-answering''': DistilBertForQuestionAnswering, '''text-classification''': DistilBertForSequenceClassification, '''token-classification''': DistilBertForTokenClassification, '''zero-shot''': DistilBertForSequenceClassification, } if is_torch_available() else {} ) snake_case__ = True snake_case__ = True snake_case__ = True snake_case__ = True def lowerCamelCase__ ( self : List[str] ): __lowerCamelCase : Union[str, Any] = DistilBertModelTester(self ) __lowerCamelCase : Dict = ConfigTester(self , config_class=A_ , dim=37 ) def lowerCamelCase__ ( self : Optional[int] ): self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Tuple ): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*A_ ) def lowerCamelCase__ ( self : Optional[Any] ): __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*A_ ) def lowerCamelCase__ ( self : List[str] ): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*A_ ) def lowerCamelCase__ ( self : str ): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*A_ ) def lowerCamelCase__ ( self : Optional[Any] ): __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*A_ ) def lowerCamelCase__ ( self : List[str] ): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*A_ ) @slow def lowerCamelCase__ ( self : List[Any] ): for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Tuple = DistilBertModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @slow @require_torch_gpu def lowerCamelCase__ ( self : List[Any] ): __lowerCamelCase , __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return __lowerCamelCase : Optional[Any] = True __lowerCamelCase : Dict = model_class(config=A_ ) __lowerCamelCase : Tuple = self._prepare_for_class(A_ , A_ ) __lowerCamelCase : Tuple = torch.jit.trace( A_ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(A_ , os.path.join(A_ , "traced_model.pt" ) ) __lowerCamelCase : Dict = torch.jit.load(os.path.join(A_ , "traced_model.pt" ) , map_location=A_ ) loaded(inputs_dict["input_ids"].to(A_ ) , inputs_dict["attention_mask"].to(A_ ) ) @require_torch class _snake_case ( unittest.TestCase ): @slow def lowerCamelCase__ ( self : Optional[int] ): __lowerCamelCase : List[Any] = DistilBertModel.from_pretrained("distilbert-base-uncased" ) __lowerCamelCase : List[str] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __lowerCamelCase : List[str] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCamelCase : Optional[Any] = model(A_ , attention_mask=A_ )[0] __lowerCamelCase : Optional[int] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , A_ ) __lowerCamelCase : Tuple = torch.tensor( [[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , A_ , atol=1E-4 ) )
646
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : Any ,A_ : int=13 ,A_ : str=7 ,A_ : Tuple=True ,A_ : str=True ,A_ : str=False ,A_ : List[str]=True ,A_ : str=99 ,A_ : str=32 ,A_ : Optional[int]=5 ,A_ : Optional[Any]=4 ,A_ : str=37 ,A_ : Optional[Any]="gelu" ,A_ : Union[str, Any]=0.1 ,A_ : Any=0.1 ,A_ : Optional[Any]=512 ,A_ : str=16 ,A_ : int=2 ,A_ : Optional[Any]=0.02 ,A_ : str=3 ,A_ : str=4 ,A_ : List[str]=None ,) -> str: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = scope def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: return LlamaConfig( 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : Optional[int] ,A_ : Any ,A_ : Optional[Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ) -> List[Any]: A = LlamaModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : int ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Dict ,) -> List[str]: A = True A = LlamaModel(A_ ) model.to(A_ ) model.eval() A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,) A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict ,A_ : Dict ,A_ : Tuple ,A_ : Tuple ,A_ : Dict ,) -> Union[str, Any]: A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Dict ,A_ : Any ,A_ : int ,A_ : List[str] ,A_ : Tuple ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : int ,) -> List[Any]: A = True A = True A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() # first forward pass A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,use_cache=A_ ,) A = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A = ids_tensor((self.batch_size, 3) ,config.vocab_size ) A = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and A = torch.cat([input_ids, next_tokens] ,dim=-1 ) A = torch.cat([input_mask, next_mask] ,dim=-1 ) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,past_key_values=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] # select random slice A = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A = output_from_no_past[:, -3:, random_slice_idx].detach() A = 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 _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _lowerCamelCase: List[Any] = (LlamaForCausalLM,) if is_torch_available() else () _lowerCamelCase: Any = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) _lowerCamelCase: int = False _lowerCamelCase: List[str] = False def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = LlamaModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A = type self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'single_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'multi_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ) -> str: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = ids_tensor([1, 10] ,config.vocab_size ) A = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = LlamaModel(A_ ) original_model.to(A_ ) original_model.eval() A = original_model(A_ ).last_hidden_state A = original_model(A_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = {'type': scaling_type, 'factor': 10.0} A = LlamaModel(A_ ) scaled_model.to(A_ ) scaled_model.eval() A = scaled_model(A_ ).last_hidden_state A = scaled_model(A_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' ,device_map='auto' ) A = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 A = torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) A = torch.tensor( [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # fmt: off A = torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' A = 'Simply put, the theory of relativity states that ' A = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) A = tokenizer.encode(A_ ,return_tensors='pt' ) A = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' ,device_map='sequential' ,use_safetensors=A_ ) # greedy generation outputs A = model.generate(A_ ,max_new_tokens=64 ,top_p=A_ ,temperature=1 ,do_sample=A_ ) A = tokenizer.decode(generated_ids[0] ,skip_special_tokens=A_ ) self.assertEqual(A_ ,A_ )
91
0
'''simple docstring''' import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowercase ( _lowercase , unittest.TestCase ): _a = ConsistencyModelPipeline _a = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _a = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt _a = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def UpperCamelCase__ ( self ) -> List[Any]: __a = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def UpperCamelCase__ ( self ) -> Optional[Any]: __a = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def UpperCamelCase__ ( self , UpperCamelCase=False ) -> Tuple: if class_cond: __a = self.dummy_cond_unet else: __a = self.dummy_uncond_unet # Default to CM multistep sampler __a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __a = { 'unet': unet, 'scheduler': scheduler, } return components def UpperCamelCase__ ( self , UpperCamelCase , UpperCamelCase=0 ) -> int: if str(A_ ).startswith('mps' ): __a = torch.manual_seed(A_ ) else: __a = torch.Generator(device=A_ ).manual_seed(A_ ) __a = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def UpperCamelCase__ ( self ) -> Dict: __a = 'cpu' # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = ConsistencyModelPipeline(**A_ ) __a = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_dummy_inputs(A_ ) __a = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) -> Dict: __a = 'cpu' # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components(class_cond=A_ ) __a = ConsistencyModelPipeline(**A_ ) __a = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_dummy_inputs(A_ ) __a = 0 __a = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) -> Optional[Any]: __a = 'cpu' # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = ConsistencyModelPipeline(**A_ ) __a = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_dummy_inputs(A_ ) __a = 1 __a = None __a = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) -> Any: __a = 'cpu' # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components(class_cond=A_ ) __a = ConsistencyModelPipeline(**A_ ) __a = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_dummy_inputs(A_ ) __a = 1 __a = None __a = 0 __a = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class __lowercase ( unittest.TestCase ): def UpperCamelCase__ ( self ) -> str: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self , UpperCamelCase=0 , UpperCamelCase=False , UpperCamelCase="cpu" , UpperCamelCase=torch.floataa , UpperCamelCase=(1, 3, 64, 64) ) -> Tuple: __a = torch.manual_seed(A_ ) __a = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __a = self.get_fixed_latents(seed=A_ , device=A_ , dtype=A_ , shape=A_ ) __a = latents return inputs def UpperCamelCase__ ( self , UpperCamelCase=0 , UpperCamelCase="cpu" , UpperCamelCase=torch.floataa , UpperCamelCase=(1, 3, 64, 64) ) -> List[Any]: if type(A_ ) == str: __a = torch.device(A_ ) __a = torch.Generator(device=A_ ).manual_seed(A_ ) __a = randn_tensor(A_ , generator=A_ , device=A_ , dtype=A_ ) return latents def UpperCamelCase__ ( self ) -> List[str]: __a = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __a = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_inputs() __a = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.0_888, 0.0_881, 0.0_666, 0.0_479, 0.0_292, 0.0_195, 0.0_201, 0.0_163, 0.0_254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def UpperCamelCase__ ( self ) -> List[str]: __a = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __a = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_inputs() __a = 1 __a = None __a = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.0_340, 0.0_152, 0.0_063, 0.0_267, 0.0_221, 0.0_107, 0.0_416, 0.0_186, 0.0_217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def UpperCamelCase__ ( self ) -> List[str]: __a = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __a = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_inputs(get_fixed_latents=A_ , device=A_ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=A_ , enable_math=A_ , enable_mem_efficient=A_ ): __a = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.1_875, 0.1_428, 0.1_289, 0.2_151, 0.2_092, 0.1_477, 0.1_877, 0.1_641, 0.1_353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def UpperCamelCase__ ( self ) -> List[Any]: __a = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __a = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=A_ ) __a = self.get_inputs(get_fixed_latents=A_ , device=A_ ) __a = 1 __a = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=A_ , enable_math=A_ , enable_mem_efficient=A_ ): __a = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __a = image[0, -3:, -3:, -1] __a = np.array([0.1_663, 0.1_948, 0.2_275, 0.1_680, 0.1_204, 0.1_245, 0.1_858, 0.1_338, 0.2_095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
539
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers _lowercase = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def _snake_case ( ): A = os.path.dirname(os.path.realpath(snake_case__ ) ) A = os.path.join(snake_case__ , 'words.txt' ) A = '' with open(snake_case__ ) as f: A = f.readline() A = [word.strip('"' ) for word in words.strip('\r\n' ).split(',' )] A = [ word for word in [sum(ord(snake_case__ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(snake_case__ ) if __name__ == "__main__": print(solution())
91
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def snake_case (UpperCAmelCase__ ) -> Tuple: UpperCamelCase_: Union[str, Any] = 3_8_4 if "tiny" in model_name: UpperCamelCase_: Dict = [3, 3, 9, 3] UpperCamelCase_: int = [9_6, 1_9_2, 3_8_4, 7_6_8] if "small" in model_name: UpperCamelCase_: List[str] = [3, 3, 2_7, 3] UpperCamelCase_: str = [9_6, 1_9_2, 3_8_4, 7_6_8] if "base" in model_name: UpperCamelCase_: Any = [3, 3, 2_7, 3] UpperCamelCase_: Tuple = [1_2_8, 2_5_6, 5_1_2, 1_0_2_4] UpperCamelCase_: Optional[int] = 5_1_2 if "large" in model_name: UpperCamelCase_: Optional[int] = [3, 3, 2_7, 3] UpperCamelCase_: List[str] = [1_9_2, 3_8_4, 7_6_8, 1_5_3_6] UpperCamelCase_: List[Any] = 7_6_8 if "xlarge" in model_name: UpperCamelCase_: Dict = [3, 3, 2_7, 3] UpperCamelCase_: int = [2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] UpperCamelCase_: List[str] = 1_0_2_4 # set label information UpperCamelCase_: Tuple = 1_5_0 UpperCamelCase_: Union[str, Any] = 'huggingface/label-files' UpperCamelCase_: Optional[Any] = 'ade20k-id2label.json' UpperCamelCase_: Dict = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) UpperCamelCase_: List[Any] = {int(snake_case__ ): v for k, v in idalabel.items()} UpperCamelCase_: List[Any] = {v: k for k, v in idalabel.items()} UpperCamelCase_: Optional[int] = ConvNextConfig( depths=snake_case__ , hidden_sizes=snake_case__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) UpperCamelCase_: Optional[int] = UperNetConfig( backbone_config=snake_case__ , auxiliary_in_channels=snake_case__ , num_labels=snake_case__ , idalabel=snake_case__ , labelaid=snake_case__ , ) return config def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Union[str, Any] = [] # fmt: off # stem rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight') ) rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias') ) rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight') ) rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.stages.{i}.{j}.gamma''', F'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.norm.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.norm.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((F'''backbone.downsample_layers.{i}.0.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.0.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.1.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.1.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((F'''backbone.norm{i}.weight''', F'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((F'''backbone.norm{i}.bias''', F'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'), ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'), ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'), ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'), ] ) # fmt: on return rename_keys def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> str: UpperCamelCase_: Optional[Any] = dct.pop(snake_case__ ) UpperCamelCase_: str = val def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> int: UpperCamelCase_: List[str] = { 'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth', 'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth', 'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth', 'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth', 'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth', } UpperCamelCase_: Dict = model_name_to_url[model_name] UpperCamelCase_: str = torch.hub.load_state_dict_from_url(snake_case__ , map_location='cpu' )['state_dict'] UpperCamelCase_: List[str] = get_upernet_config(snake_case__ ) UpperCamelCase_: Tuple = UperNetForSemanticSegmentation(snake_case__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): UpperCamelCase_: List[str] = state_dict.pop(snake_case__ ) if "bn" in key: UpperCamelCase_: List[Any] = key.replace('bn' , 'batch_norm' ) UpperCamelCase_: List[str] = val # rename keys UpperCamelCase_: List[str] = create_rename_keys(snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ ) # verify on image UpperCamelCase_: str = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' UpperCamelCase_: Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ).convert('RGB' ) UpperCamelCase_: Optional[int] = SegformerImageProcessor() UpperCamelCase_: Union[str, Any] = processor(snake_case__ , return_tensors='pt' ).pixel_values with torch.no_grad(): UpperCamelCase_: Tuple = model(snake_case__ ) if model_name == "upernet-convnext-tiny": UpperCamelCase_: List[str] = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": UpperCamelCase_: Optional[int] = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": UpperCamelCase_: List[Any] = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": UpperCamelCase_: List[str] = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": UpperCamelCase_: Tuple = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print('Logits:' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , snake_case__ , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(snake_case__ ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(snake_case__ ) if push_to_hub: print(F'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(F'''openmmlab/{model_name}''' ) processor.push_to_hub(F'''openmmlab/{model_name}''' ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-convnext-tiny', type=str, choices=[F'''upernet-convnext-{size}''' for size in ['tiny', 'small', 'base', 'large', 'xlarge']], help='Name of the ConvNext UperNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) A_ : int = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
57
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''', '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''mobilenet_v1''' def __init__( self : Optional[int] ,A_ : Optional[int]=3 ,A_ : Any=224 ,A_ : List[Any]=1.0 ,A_ : Union[str, Any]=8 ,A_ : Union[str, Any]="relu6" ,A_ : Optional[Any]=True ,A_ : List[str]=0.9_99 ,A_ : int=0.02 ,A_ : int=0.0_01 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) A = num_channels A = image_size A = depth_multiplier A = min_depth A = hidden_act A = tf_padding A = classifier_dropout_prob A = initializer_range A = layer_norm_eps class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> float: return 1e-4
91
0
import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input lowercase__ ='Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def __UpperCamelCase ( ): __a : Optional[Any] = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __a : str = get_sagemaker_input() else: __a : Tuple = get_cluster_input() return config def __UpperCamelCase ( lowerCAmelCase__ : Any=None ): if subparsers is not None: __a : Tuple = subparsers.add_parser('''config''' , description=snake_case__ ) else: __a : List[Any] = argparse.ArgumentParser('''Accelerate config command''' , description=snake_case__ ) parser.add_argument( '''--config_file''' , default=snake_case__ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=snake_case__ ) return parser def __UpperCamelCase ( lowerCAmelCase__ : Tuple ): __a : Union[str, Any] = get_user_input() if args.config_file is not None: __a : Dict = args.config_file else: if not os.path.isdir(snake_case__ ): os.makedirs(snake_case__ ) __a : Union[str, Any] = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(snake_case__ ) else: config.to_yaml_file(snake_case__ ) print(f"accelerate configuration saved at {config_file}" ) def __UpperCamelCase ( ): __a : Dict = config_command_parser() __a : Dict = parser.parse_args() config_command(snake_case__ ) if __name__ == "__main__": main()
521
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ElectraForCausalLM''', '''ElectraForMaskedLM''', '''ElectraForMultipleChoice''', '''ElectraForPreTraining''', '''ElectraForQuestionAnswering''', '''ElectraForSequenceClassification''', '''ElectraForTokenClassification''', '''ElectraModel''', '''ElectraPreTrainedModel''', '''load_tf_weights_in_electra''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFElectraForMaskedLM''', '''TFElectraForMultipleChoice''', '''TFElectraForPreTraining''', '''TFElectraForQuestionAnswering''', '''TFElectraForSequenceClassification''', '''TFElectraForTokenClassification''', '''TFElectraModel''', '''TFElectraPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxElectraForCausalLM''', '''FlaxElectraForMaskedLM''', '''FlaxElectraForMultipleChoice''', '''FlaxElectraForPreTraining''', '''FlaxElectraForQuestionAnswering''', '''FlaxElectraForSequenceClassification''', '''FlaxElectraForTokenClassification''', '''FlaxElectraModel''', '''FlaxElectraPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
def _a ( ) -> Dict: for n in range(1 , 1_000_000 ): yield n * (n + 1) // 2 def _a ( a :List[Any] ) -> int: a = 1 a = 2 while i * i <= n: a = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _a ( ) -> List[str]: return next(i for i in triangle_number_generator() if count_divisors(snake_case__ ) > 500 ) if __name__ == "__main__": print(solution())
117
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal _lowercase = datasets.utils.logging.get_logger(__name__) _lowercase = ['''names''', '''prefix'''] _lowercase = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] _lowercase = ['''encoding_errors''', '''on_bad_lines'''] _lowercase = ['''date_format'''] @dataclass class lowerCAmelCase_ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCamelCase: str = "," _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[int, List[int], str]] = "infer" _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[Union[int, str, List[int], List[str]]] = None _lowerCamelCase: Optional[Union[List[int], List[str]]] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: Optional[Literal["c", "python", "pyarrow"]] = None _lowerCamelCase: Dict[Union[int, str], Callable[[Any], Any]] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: bool = False _lowerCamelCase: Optional[Union[int, List[int]]] = None _lowerCamelCase: Optional[int] = None _lowerCamelCase: Optional[Union[str, List[str]]] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: bool = True _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = "." _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = '"' _lowerCamelCase: int = 0 _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: int = 0 _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: Optional[str] = None _lowerCamelCase: int = 10000 _lowerCamelCase: Optional[datasets.Features] = None _lowerCamelCase: Optional[str] = "strict" _lowerCamelCase: Literal["error", "warn", "skip"] = "error" _lowerCamelCase: Optional[str] = None def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: if self.delimiter is not None: A = self.delimiter if self.column_names is not None: A = self.column_names @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() ,A_ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class lowerCAmelCase_ ( datasets.ArrowBasedBuilder ): '''simple docstring''' _lowerCamelCase: Any = CsvConfig def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return datasets.DatasetInfo(features=self.config.features ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Any ) -> str: if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A_ ,(str, list, tuple) ): A = data_files if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,gen_kwargs={'files': files} )] A = [] for split_name, files in data_files.items(): if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] splits.append(datasets.SplitGenerator(name=A_ ,gen_kwargs={'files': files} ) ) return splits def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : pa.Table ) -> pa.Table: if self.config.features is not None: A = self.config.features.arrow_schema if all(not require_storage_cast(A_ ) for feature in self.config.features.values() ): # cheaper cast A = pa.Table.from_arrays([pa_table[field.name] for field in schema] ,schema=A_ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A = table_cast(A_ ,A_ ) return pa_table def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ) -> List[Any]: A = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(A_ ) else object for name, dtype, feature in zip(schema.names ,schema.types ,self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(A_ ) ): A = pd.read_csv(A_ ,iterator=A_ ,dtype=A_ ,**self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(A_ ): A = pa.Table.from_pandas(A_ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A_ ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(A_ )}: {e}' ) raise
91
0
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class _UpperCAmelCase : '''simple docstring''' a__ =42 # setable values a__ =42 a__ =42 a__ =None @classmethod def __lowerCAmelCase ( cls , A , A , A ) -> Union[str, Any]: return cls(common=A_ , init_noise_sigma=A_ , timesteps=A_ ) @dataclass class _UpperCAmelCase ( _lowercase ): '''simple docstring''' a__ =42 class _UpperCAmelCase ( _lowercase ,_lowercase ): '''simple docstring''' a__ =[e.name for e in FlaxKarrasDiffusionSchedulers] a__ =42 @property def __lowerCAmelCase ( self ) -> Union[str, Any]: return True @register_to_config def __init__( self , A = 1_0_0_0 , A = 0.0_001 , A = 0.02 , A = "linear" , A = None , A = "fixed_small" , A = True , A = "epsilon" , A = jnp.floataa , ) -> Union[str, Any]: _UpperCAmelCase : Dict = dtype def __lowerCAmelCase ( self , A = None ) -> DDPMSchedulerState: if common is None: _UpperCAmelCase : List[str] = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution _UpperCAmelCase : Any = jnp.array(1.0 , dtype=self.dtype ) _UpperCAmelCase : Any = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=A_ , init_noise_sigma=A_ , timesteps=A_ , ) def __lowerCAmelCase ( self , A , A , A = None ) -> jnp.ndarray: return sample def __lowerCAmelCase ( self , A , A , A = () ) -> DDPMSchedulerState: _UpperCAmelCase : int = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 _UpperCAmelCase : Any = (jnp.arange(0 , A_ ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=A_ , timesteps=A_ , ) def __lowerCAmelCase ( self , A , A , A=None , A=None ) -> Optional[int]: _UpperCAmelCase : List[str] = state.common.alphas_cumprod[t] _UpperCAmelCase : Optional[Any] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _UpperCAmelCase : Tuple = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: _UpperCAmelCase : List[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": _UpperCAmelCase : Optional[int] = jnp.clip(A_ , a_min=1E-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": _UpperCAmelCase : Tuple = jnp.log(jnp.clip(A_ , a_min=1E-20 ) ) elif variance_type == "fixed_large": _UpperCAmelCase : Tuple = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log _UpperCAmelCase : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": _UpperCAmelCase : Optional[int] = variance _UpperCAmelCase : Dict = state.common.betas[t] _UpperCAmelCase : int = (predicted_variance + 1) / 2 _UpperCAmelCase : Dict = frac * max_log + (1 - frac) * min_log return variance def __lowerCAmelCase ( self , A , A , A , A , A = None , A = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: _UpperCAmelCase : Optional[int] = timestep if key is None: _UpperCAmelCase : Any = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: _UpperCAmelCase , _UpperCAmelCase : str = jnp.split(A_ , sample.shape[1] , axis=1 ) else: _UpperCAmelCase : Any = None # 1. compute alphas, betas _UpperCAmelCase : int = state.common.alphas_cumprod[t] _UpperCAmelCase : Optional[Any] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) _UpperCAmelCase : Union[str, Any] = 1 - alpha_prod_t _UpperCAmelCase : Tuple = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _UpperCAmelCase : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _UpperCAmelCase : int = model_output elif self.config.prediction_type == "v_prediction": _UpperCAmelCase : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: _UpperCAmelCase : Union[str, Any] = jnp.clip(A_ , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _UpperCAmelCase : int = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t _UpperCAmelCase : int = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _UpperCAmelCase : List[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): _UpperCAmelCase : List[Any] = jax.random.split(A_ , num=1 ) _UpperCAmelCase : Optional[int] = jax.random.normal(A_ , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(A_ , A_ , predicted_variance=A_ ) ** 0.5) * noise _UpperCAmelCase : Optional[int] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) _UpperCAmelCase : List[Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=A_ , state=A_ ) def __lowerCAmelCase ( self , A , A , A , A , ) -> jnp.ndarray: return add_noise_common(state.common , A_ , A_ , A_ ) def __lowerCAmelCase ( self , A , A , A , A , ) -> jnp.ndarray: return get_velocity_common(state.common , A_ , A_ , A_ ) def __len__( self ) -> List[str]: return self.config.num_train_timesteps
506
"""simple docstring""" from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Any ,A_ : Callable ,A_ : Optional[Features] = None ,A_ : str = None ,A_ : bool = False ,A_ : bool = False ,A_ : Optional[dict] = None ,A_ : Optional[int] = None ,**A_ : int ,) -> str: super().__init__( features=A_ ,cache_dir=A_ ,keep_in_memory=A_ ,streaming=A_ ,num_proc=A_ ,**A_ ,) A = Generator( cache_dir=A_ ,features=A_ ,generator=A_ ,gen_kwargs=A_ ,**A_ ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: # Build iterable dataset if self.streaming: A = self.builder.as_streaming_dataset(split='train' ) # Build regular (map-style) dataset else: A = None A = None A = None A = None self.builder.download_and_prepare( download_config=A_ ,download_mode=A_ ,verification_mode=A_ ,base_path=A_ ,num_proc=self.num_proc ,) A = self.builder.as_dataset( split='train' ,verification_mode=A_ ,in_memory=self.keep_in_memory ) return dataset
91
0
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : BertModel , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> Dict: _lowercase = ("""dense.weight""", """attention.self.query""", """attention.self.key""", """attention.self.value""") _lowercase = ( ("""layer.""", """layer_"""), ("""word_embeddings.weight""", """word_embeddings"""), ("""position_embeddings.weight""", """position_embeddings"""), ("""token_type_embeddings.weight""", """token_type_embeddings"""), (""".""", """/"""), ("""LayerNorm/weight""", """LayerNorm/gamma"""), ("""LayerNorm/bias""", """LayerNorm/beta"""), ("""weight""", """kernel"""), ) if not os.path.isdir(snake_case__ ): os.makedirs(snake_case__ ) _lowercase = model.state_dict() def to_tf_var_name(SCREAMING_SNAKE_CASE_ : str ): for patt, repl in iter(snake_case__ ): _lowercase = name.replace(snake_case__ , snake_case__ ) return f"""bert/{name}""" def create_tf_var(SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : tf.Session ): _lowercase = tf.dtypes.as_dtype(tensor.dtype ) _lowercase = tf.get_variable(dtype=snake_case__ , shape=tensor.shape , name=snake_case__ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(snake_case__ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: _lowercase = to_tf_var_name(snake_case__ ) _lowercase = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): _lowercase = torch_tensor.T _lowercase = create_tf_var(tensor=snake_case__ , name=snake_case__ , session=snake_case__ ) tf.keras.backend.set_value(snake_case__ , snake_case__ ) _lowercase = session.run(snake_case__ ) print(f"""Successfully created {tf_name}: {np.allclose(snake_case__ , snake_case__ )}""" ) _lowercase = tf.train.Saver(tf.trainable_variables() ) saver.save(snake_case__ , os.path.join(snake_case__ , model_name.replace("""-""" , """_""" ) + """.ckpt""" ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : Tuple=None ) -> Optional[int]: _lowercase = argparse.ArgumentParser() parser.add_argument("""--model_name""" , type=snake_case__ , required=snake_case__ , help="""model name e.g. bert-base-uncased""" ) parser.add_argument( """--cache_dir""" , type=snake_case__ , default=snake_case__ , required=snake_case__ , help="""Directory containing pytorch model""" ) parser.add_argument("""--pytorch_model_path""" , type=snake_case__ , required=snake_case__ , help="""/path/to/<pytorch-model-name>.bin""" ) parser.add_argument("""--tf_cache_dir""" , type=snake_case__ , required=snake_case__ , help="""Directory in which to save tensorflow model""" ) _lowercase = parser.parse_args(snake_case__ ) _lowercase = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=snake_case__ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
287
"""simple docstring""" from maths.prime_check import is_prime def _snake_case ( snake_case__ : int ): if not isinstance(snake_case__ , snake_case__ ): A = F'Input value of [number={number}] must be an integer' raise TypeError(snake_case__ ) if is_prime(snake_case__ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
91
0
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __snake_case( _lowercase ): '''simple docstring''' UpperCAmelCase : List[str] = ['''image_processor''', '''tokenizer'''] UpperCAmelCase : Optional[int] = '''Pix2StructImageProcessor''' UpperCAmelCase : Dict = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , A_ , A_ ) -> int: lowerCAmelCase = False super().__init__(A_ , A_ ) def __call__( self , A_=None , A_ = None , A_ = True , A_ = False , A_ = None , A_ = None , A_ = 2048 , A_ = 0 , A_ = None , A_ = None , A_ = False , A_ = False , A_ = False , A_ = False , A_ = False , A_ = True , A_ = None , **A_ , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None and not self.image_processor.is_vqa: lowerCAmelCase = self.tokenizer lowerCAmelCase = self.tokenizer( text=A_ , add_special_tokens=A_ , padding=A_ , truncation=A_ , max_length=A_ , stride=A_ , pad_to_multiple_of=A_ , return_attention_mask=A_ , return_overflowing_tokens=A_ , return_special_tokens_mask=A_ , return_offsets_mapping=A_ , return_token_type_ids=A_ , return_length=A_ , verbose=A_ , return_tensors=A_ , **A_ , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values lowerCAmelCase = self.image_processor( A_ , return_tensors=A_ , max_patches=A_ , **A_ ) else: # add pixel_values and bbox lowerCAmelCase = self.image_processor( A_ , return_tensors=A_ , max_patches=A_ , header_text=A_ , **A_ ) if text is not None and not self.image_processor.is_vqa: lowerCAmelCase = self.tokenizer( text=A_ , add_special_tokens=A_ , padding=A_ , truncation=A_ , max_length=A_ , stride=A_ , pad_to_multiple_of=A_ , return_attention_mask=A_ , return_overflowing_tokens=A_ , return_special_tokens_mask=A_ , return_offsets_mapping=A_ , return_token_type_ids=A_ , return_length=A_ , verbose=A_ , return_tensors=A_ , **A_ , ) if "attention_mask" in text_encoding: lowerCAmelCase = text_encoding.pop("""attention_mask""" ) if "input_ids" in text_encoding: lowerCAmelCase = text_encoding.pop("""input_ids""" ) else: lowerCAmelCase = None if text_encoding is not None: encoding_image_processor.update(A_ ) return encoding_image_processor def __snake_case ( self , *A_ , **A_ ) -> Union[str, Any]: return self.tokenizer.batch_decode(*A_ , **A_ ) def __snake_case ( self , *A_ , **A_ ) -> Any: return self.tokenizer.decode(*A_ , **A_ ) @property def __snake_case ( self ) -> Any: lowerCAmelCase = self.tokenizer.model_input_names lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
433
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[str]=0 ) -> str: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = OnnxStableDiffusionImgaImgPipeline.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_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) 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_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.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 ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
91
0
from __future__ import annotations import numpy as np def _UpperCAmelCase (UpperCamelCase__ : np.ndarray ): _A , _A : List[Any] = np.shape(snake_case__ ) if rows != columns: _A : Tuple = ( "\'table\' has to be of square shaped array but got a " f"{rows}x{columns} array:\n{table}" ) raise ValueError(snake_case__ ) _A : str = np.zeros((rows, columns) ) _A : Any = np.zeros((rows, columns) ) for i in range(snake_case__ ): for j in range(snake_case__ ): _A : List[Any] = sum(lower[i][k] * upper[k][j] for k in range(snake_case__ ) ) if upper[j][j] == 0: raise ArithmeticError("No LU decomposition exists" ) _A : int = (table[i][j] - total) / upper[j][j] _A : Optional[Any] = 1 for j in range(snake_case__ , snake_case__ ): _A : List[str] = sum(lower[i][k] * upper[k][j] for k in range(snake_case__ ) ) _A : int = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
503
"""simple docstring""" from __future__ import annotations def _snake_case ( snake_case__ : tuple[int, int] , snake_case__ : int ): A , A = position A = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] A = [] for position in positions: A , A = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(snake_case__ ) return permissible_positions def _snake_case ( snake_case__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _snake_case ( snake_case__ : list[list[int]] , snake_case__ : tuple[int, int] , snake_case__ : int ): if is_complete(snake_case__ ): return True for position in get_valid_pos(snake_case__ , len(snake_case__ ) ): A , A = position if board[y][x] == 0: A = curr + 1 if open_knight_tour_helper(snake_case__ , snake_case__ , curr + 1 ): return True A = 0 return False def _snake_case ( snake_case__ : int ): A = [[0 for i in range(snake_case__ )] for j in range(snake_case__ )] for i in range(snake_case__ ): for j in range(snake_case__ ): A = 1 if open_knight_tour_helper(snake_case__ , (i, j) , 1 ): return board A = 0 A = F'Open Kight Tour cannot be performed on a board of size {n}' raise ValueError(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod()
91
0
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowercase_ = logging.getLogger(__name__) lowercase_ = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) lowercase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={ 'help': ( 'The model checkpoint for weights initialization. Leave None if you want to train a model from' ' scratch.' ) } , ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(_lowercase )} , ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'The input training data file (a text file).'} ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={ 'help': ( 'The input training data files (multiple files in glob format). ' 'Very often splitting large files to smaller files can prevent tokenizer going out of memory' ) } , ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'An optional input train ref data file for whole word mask in Chinese.'} , ) __UpperCAmelCase : Optional[str] = field( default=_lowercase , metadata={'help': 'An optional input eval ref data file for whole word mask in Chinese.'} , ) __UpperCAmelCase : bool = field( default=_lowercase , metadata={'help': 'Whether distinct lines of text in the dataset are to be handled as distinct sequences.'} , ) __UpperCAmelCase : bool = field( default=_lowercase , metadata={'help': 'Train with masked-language modeling loss instead of language modeling.'} ) __UpperCAmelCase : bool = field(default=_lowercase , metadata={'help': 'Whether ot not to use whole word mask.'} ) __UpperCAmelCase : float = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) __UpperCAmelCase : float = field( default=1 / 6 , metadata={ 'help': ( 'Ratio of length of a span of masked tokens to surrounding context length for permutation language' ' modeling.' ) } , ) __UpperCAmelCase : int = field( default=5 , metadata={'help': 'Maximum length of a span of masked tokens for permutation language modeling.'} ) __UpperCAmelCase : int = field( default=-1 , metadata={ 'help': ( 'Optional input sequence length after tokenization.' 'The training dataset will be truncated in block of this size for training.' 'Default to the model max input length for single sentence inputs (take into account special tokens).' ) } , ) __UpperCAmelCase : bool = field( default=_lowercase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def lowercase ( lowerCAmelCase__ : DataTrainingArguments , lowerCAmelCase__ : PreTrainedTokenizer , lowerCAmelCase__ : bool = False , lowerCAmelCase__ : Optional[str] = None , ) -> int: def _dataset(lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError('''You need to set world whole masking and mlm to True for Chinese Whole Word Mask''' ) return LineByLineWithRefDataset( tokenizer=snake_case__ , file_path=snake_case__ , block_size=args.block_size , ref_path=snake_case__ , ) return LineByLineTextDataset(tokenizer=snake_case__ , file_path=snake_case__ , block_size=args.block_size ) else: return TextDataset( tokenizer=snake_case__ , file_path=snake_case__ , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=snake_case__ , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(snake_case__ ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def lowercase ( ) -> int: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __a = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) __a , __a , __a = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( '''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file ''' '''or remove the --do_eval argument.''' ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , snake_case__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: __a = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: __a = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: __a = CONFIG_MAPPING[model_args.model_type]() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.tokenizer_name: __a = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: __a = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another''' ''' script, save it,and load it from here, using --tokenizer_name''' ) if model_args.model_name_or_path: __a = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case__ , cache_dir=model_args.cache_dir , ) else: logger.info('''Training new model from scratch''' ) __a = AutoModelWithLMHead.from_config(snake_case__ ) model.resize_token_embeddings(len(snake_case__ ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( '''BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the''' '''--mlm flag (masked language modeling).''' ) if data_args.block_size <= 0: __a = tokenizer.max_len # Our input block size will be the max possible for the model else: __a = min(data_args.block_size , tokenizer.max_len ) # Get datasets __a = ( get_dataset(snake_case__ , tokenizer=snake_case__ , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) __a = ( get_dataset(snake_case__ , tokenizer=snake_case__ , evaluate=snake_case__ , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": __a = DataCollatorForPermutationLanguageModeling( tokenizer=snake_case__ , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: __a = DataCollatorForWholeWordMask( tokenizer=snake_case__ , mlm_probability=data_args.mlm_probability ) else: __a = DataCollatorForLanguageModeling( tokenizer=snake_case__ , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer __a = Trainer( model=snake_case__ , args=snake_case__ , data_collator=snake_case__ , train_dataset=snake_case__ , eval_dataset=snake_case__ , prediction_loss_only=snake_case__ , ) # Training if training_args.do_train: __a = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=snake_case__ ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __a = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __a = trainer.evaluate() __a = math.exp(eval_output['''eval_loss'''] ) __a = {'''perplexity''': perplexity} __a = os.path.join(training_args.output_dir , '''eval_results_lm.txt''' ) if trainer.is_world_master(): with open(snake_case__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key in sorted(result.keys() ): logger.info(''' %s = %s''' , snake_case__ , str(result[key] ) ) writer.write('''%s = %s\n''' % (key, str(result[key] )) ) results.update(snake_case__ ) return results def lowercase ( lowerCAmelCase__ : List[str] ) -> Tuple: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
695
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Optional[int] = BlenderbotSmallTokenizer _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: super().setUp() A = ['__start__', 'adapt', 'act', 'ap@@', 'te', '__end__', '__unk__'] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['#version: 0.2', 'a p', 't e</w>', 'ap t</w>', 'a d', 'ad apt</w>', 'a c', 'ac t</w>', ''] A = {'unk_token': '__unk__', 'bos_token': '__start__', 'eos_token': '__end__'} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,**A_ : Union[str, Any] ) -> Optional[int]: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Tuple ) -> List[Any]: A = 'adapt act apte' A = 'adapt act apte' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: A = BlenderbotSmallTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) A = 'adapt act apte' A = ['adapt', 'act', 'ap@@', 'te'] A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] A = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) assert tok('sam' ).input_ids == [1384] A = 'I am a small frog.' A = tok([src_text] ,padding=A_ ,truncation=A_ )['input_ids'] A = tok.batch_decode(A_ ,skip_special_tokens=A_ ,clean_up_tokenization_spaces=A_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) A = 'I am a small frog .' A = '.' A = tok(A_ )['input_ids'] A = tok(A_ )['input_ids'] assert encoded[-1] == encoded_dot[0]
91
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=_lowercase ) class lowerCAmelCase_ ( _lowercase ): """simple docstring""" _snake_case : str = field(default="""audio-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) _snake_case : ClassVar[Features] = Features({"""audio""": Audio()} ) _snake_case : ClassVar[Features] = Features({"""labels""": ClassLabel} ) _snake_case : str = "audio" _snake_case : str = "labels" def __a ( self :List[Any] , lowerCamelCase__ :int ): 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__ :Optional[Any] = copy.deepcopy(self ) UpperCamelCase__ :List[Any] = self.label_schema.copy() UpperCamelCase__ :int = features[self.label_column] UpperCamelCase__ :Optional[int] = label_schema return task_template @property def __a ( self :Any ): return { self.audio_column: "audio", self.label_column: "labels", }
45
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''image_processor''', '''tokenizer'''] _lowerCamelCase: Optional[int] = '''Pix2StructImageProcessor''' _lowerCamelCase: Dict = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : Optional[int] ,A_ : List[str] ,A_ : Optional[int] ) -> int: A = False super().__init__(A_ ,A_ ) def __call__( self : Any ,A_ : List[str]=None ,A_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,A_ : bool = True ,A_ : Union[bool, str, PaddingStrategy] = False ,A_ : Union[bool, str, TruncationStrategy] = None ,A_ : Optional[int] = None ,A_ : Optional[int] = 2048 ,A_ : int = 0 ,A_ : Optional[int] = None ,A_ : Optional[bool] = None ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = True ,A_ : Optional[Union[str, TensorType]] = None ,**A_ : Tuple ,) -> BatchEncoding: if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None and not self.image_processor.is_vqa: A = self.tokenizer A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,**A_ ) else: # add pixel_values and bbox A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,header_text=A_ ,**A_ ) if text is not None and not self.image_processor.is_vqa: A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) if "attention_mask" in text_encoding: A = text_encoding.pop('attention_mask' ) if "input_ids" in text_encoding: A = text_encoding.pop('input_ids' ) else: A = None if text_encoding is not None: encoding_image_processor.update(A_ ) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,*A_ : Optional[Any] ,**A_ : Dict ) -> Union[str, Any]: return self.tokenizer.batch_decode(*A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,*A_ : Tuple ,**A_ : List[str] ) -> Any: return self.tokenizer.decode(*A_ ,**A_ ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: A = self.tokenizer.model_input_names A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
91
0
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def lowercase_ ( _lowerCamelCase: Tuple ) -> Optional[int]: '''simple docstring''' return 1 / (1 + np.exp(-z )) def lowercase_ ( _lowerCamelCase: Optional[Any] , _lowerCamelCase: Tuple ) -> int: '''simple docstring''' return (-y * np.log(snake_case__ ) - (1 - y) * np.log(1 - h )).mean() def lowercase_ ( _lowerCamelCase: Optional[int] , _lowerCamelCase: Optional[int] , _lowerCamelCase: Union[str, Any] ) -> Any: '''simple docstring''' __lowerCamelCase : Union[str, Any] = np.dot(snake_case__ , snake_case__ ) return np.sum(y * scores - np.log(1 + np.exp(snake_case__ ) ) ) def lowercase_ ( _lowerCamelCase: str , _lowerCamelCase: List[Any] , _lowerCamelCase: Dict , _lowerCamelCase: List[Any]=70000 ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase : int = np.zeros(x.shape[1] ) for iterations in range(snake_case__ ): __lowerCamelCase : str = np.dot(snake_case__ , snake_case__ ) __lowerCamelCase : Optional[int] = sigmoid_function(snake_case__ ) __lowerCamelCase : Optional[int] = np.dot(x.T , h - y ) / y.size __lowerCamelCase : int = theta - alpha * gradient # updating the weights __lowerCamelCase : Union[str, Any] = np.dot(snake_case__ , snake_case__ ) __lowerCamelCase : Tuple = sigmoid_function(snake_case__ ) __lowerCamelCase : Optional[int] = cost_function(snake_case__ , snake_case__ ) if iterations % 100 == 0: print(F"""loss: {j} \t""" ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": __A = datasets.load_iris() __A = iris.data[:, :2] __A = (iris.target != 0) * 1 __A = 0.1 __A = logistic_reg(alpha, x, y, max_iterations=70000) print('''theta: ''', theta) # printing the theta i.e our weights vector def lowercase_ ( _lowerCamelCase: Optional[int] ) -> Union[str, Any]: '''simple docstring''' return sigmoid_function( np.dot(snake_case__ , snake_case__ ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''') plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''') ((__A), (__A)) = (x[:, 0].min(), x[:, 0].max()) ((__A), (__A)) = (x[:, 1].min(), x[:, 1].max()) ((__A), (__A)) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) __A = np.c_[xxa.ravel(), xxa.ravel()] __A = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''') plt.legend() plt.show()
646
"""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 _lowercase = logging.get_logger(__name__) _lowercase = '''▁''' _lowercase = {'''vocab_file''': '''sentencepiece.bpe.model'''} _lowercase = { '''vocab_file''': { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model''' ), } } _lowercase = { '''xlm-roberta-base''': 5_12, '''xlm-roberta-large''': 5_12, '''xlm-roberta-large-finetuned-conll02-dutch''': 5_12, '''xlm-roberta-large-finetuned-conll02-spanish''': 5_12, '''xlm-roberta-large-finetuned-conll03-english''': 5_12, '''xlm-roberta-large-finetuned-conll03-german''': 5_12, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[str] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] ,A_ : str ,A_ : str="<s>" ,A_ : Any="</s>" ,A_ : Tuple="</s>" ,A_ : Any="<s>" ,A_ : Optional[Any]="<unk>" ,A_ : int="<pad>" ,A_ : str="<mask>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : Optional[int] ,) -> None: # Mask token behave like a normal word, i.e. include the space before it A = AddedToken(A_ ,lstrip=A_ ,rstrip=A_ ) if isinstance(A_ ,A_ ) else mask_token A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,sep_token=A_ ,cls_token=A_ ,pad_token=A_ ,mask_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) A = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token A = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab A = 1 A = len(self.sp_model ) + self.fairseq_offset A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ) -> Any: A = self.__dict__.copy() A = None A = self.sp_model.serialized_model_proto() return state def __setstate__( self : str ,A_ : str ) -> Optional[Any]: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A = [self.cls_token_id] A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: A = [self.sep_token_id] A = [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 _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[Any] ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] A = self.sp_model.PieceToId(A_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> int: 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 _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = ''.join(A_ ).replace(A_ ,' ' ).strip() return out_string def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
91
0
'''simple docstring''' import random class __lowercase : @staticmethod def UpperCamelCase__ ( UpperCamelCase ) -> tuple[list[int], list[int]]: __a = [ord(A_ ) for i in text] __a = [] __a = [] for i in plain: __a = random.randint(1 , 300 ) __a = (i + k) * k cipher.append(A_ ) key.append(A_ ) return cipher, key @staticmethod def UpperCamelCase__ ( UpperCamelCase , UpperCamelCase ) -> str: __a = [] for i in range(len(A_ ) ): __a = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(A_ ) ) return "".join(A_ ) if __name__ == "__main__": UpperCAmelCase_ , UpperCAmelCase_ = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
539
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal A_ : str = datasets.utils.logging.get_logger(__name__) A_ : List[str] = ['names', 'prefix'] A_ : List[str] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] A_ : Any = ['encoding_errors', 'on_bad_lines'] A_ : Union[str, Any] = ['date_format'] @dataclass class _lowerCAmelCase( datasets.BuilderConfig ): """simple docstring""" a : str ="," a : Optional[str] =None a : Optional[Union[int, List[int], str]] ="infer" a : Optional[List[str]] =None a : Optional[List[str]] =None a : Optional[Union[int, str, List[int], List[str]]] =None a : Optional[Union[List[int], List[str]]] =None a : Optional[str] =None a : bool =True a : Optional[Literal["c", "python", "pyarrow"]] =None a : Dict[Union[int, str], Callable[[Any], Any]] =None a : Optional[list] =None a : Optional[list] =None a : bool =False a : Optional[Union[int, List[int]]] =None a : Optional[int] =None a : Optional[Union[str, List[str]]] =None a : bool =True a : bool =True a : bool =False a : bool =True a : Optional[str] =None a : str ="." a : Optional[str] =None a : str ='"' a : int =0 a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : bool =True a : bool =True a : int =0 a : bool =True a : bool =False a : Optional[str] =None a : int =10000 a : Optional[datasets.Features] =None a : Optional[str] ="strict" a : Literal["error", "warn", "skip"] ="error" a : Optional[str] =None def _a ( self ): if self.delimiter is not None: UpperCamelCase_: Optional[int] = self.delimiter if self.column_names is not None: UpperCamelCase_: int = self.column_names @property def _a ( self ): UpperCamelCase_: Optional[Any] = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , A_ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class _lowerCAmelCase( datasets.ArrowBasedBuilder ): """simple docstring""" a : Any =CsvConfig def _a ( self ): return datasets.DatasetInfo(features=self.config.features ) def _a ( self , _lowerCamelCase ): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) UpperCamelCase_: int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A_ , (str, list, tuple) ): UpperCamelCase_: Union[str, Any] = data_files if isinstance(A_ , A_ ): UpperCamelCase_: Dict = [files] UpperCamelCase_: Optional[Any] = [dl_manager.iter_files(A_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] UpperCamelCase_: Optional[int] = [] for split_name, files in data_files.items(): if isinstance(A_ , A_ ): UpperCamelCase_: str = [files] UpperCamelCase_: Any = [dl_manager.iter_files(A_ ) for file in files] splits.append(datasets.SplitGenerator(name=A_ , gen_kwargs={'files': files} ) ) return splits def _a ( self , _lowerCamelCase ): if self.config.features is not None: UpperCamelCase_: Dict = self.config.features.arrow_schema if all(not require_storage_cast(A_ ) for feature in self.config.features.values() ): # cheaper cast UpperCamelCase_: Dict = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=A_ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCamelCase_: Any = table_cast(A_ , A_ ) return pa_table def _a ( self , _lowerCamelCase ): UpperCamelCase_: Optional[int] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCamelCase_: str = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(A_ ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(A_ ) ): UpperCamelCase_: Optional[int] = pd.read_csv(A_ , iterator=A_ , dtype=A_ , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(A_ ): UpperCamelCase_: Optional[Any] = pa.Table.from_pandas(A_ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A_ ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(A_ )}: {e}''' ) raise
57
"""simple docstring""" from torch import nn def _snake_case ( snake_case__ : Union[str, Any] ): 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}' )
91
0
from __future__ import annotations import math class UpperCamelCase__ : def __init__(self : str , snake_case_ : int ): __a : List[Any] = size # approximate the overall size of segment tree with given value __a : Optional[Any] = [0 for i in range(0 , 4 * size )] # create array to store lazy update __a : str = [0 for i in range(0 , 4 * size )] __a : List[str] = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowerCAmelCase (self : Union[str, Any] , snake_case_ : int ): return idx * 2 def lowerCAmelCase (self : Any , snake_case_ : int ): return idx * 2 + 1 def lowerCAmelCase (self : Any , snake_case_ : int , snake_case_ : int , snake_case_ : int , snake_case_ : list[int] ): if left_element == right_element: __a : Dict = a[left_element - 1] else: __a : Any = (left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __a : Dict = max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def lowerCAmelCase (self : List[Any] , snake_case_ : int , snake_case_ : int , snake_case_ : int , snake_case_ : int , snake_case_ : int , snake_case_ : int ): if self.flag[idx] is True: __a : List[Any] = self.lazy[idx] __a : List[Any] = False if left_element != right_element: __a : Any = self.lazy[idx] __a : Any = self.lazy[idx] __a : List[str] = True __a : Dict = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __a : Optional[int] = val if left_element != right_element: __a : Union[str, Any] = val __a : int = val __a : List[str] = True __a : Optional[int] = True return True __a : Optional[Any] = (left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __a : Any = max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def lowerCAmelCase (self : Any , snake_case_ : int , snake_case_ : int , snake_case_ : int , snake_case_ : int , snake_case_ : int ): if self.flag[idx] is True: __a : str = self.lazy[idx] __a : Union[str, Any] = False if left_element != right_element: __a : str = self.lazy[idx] __a : str = self.lazy[idx] __a : Union[str, Any] = True __a : List[Any] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __a : Optional[Any] = (left_element + right_element) // 2 __a : Union[str, Any] = self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __a : Any = self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__(self : Union[str, Any] ): return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowercase__ =[1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] lowercase__ =15 lowercase__ =SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
521
"""simple docstring""" import copy import re class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str = '''hp''' _lowerCamelCase: List[Any] = {} _lowerCamelCase: List[Any] = None @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,A_ : List[str] ,A_ : Optional[Any] ) -> Tuple: A = prefix A = defaults cls.build_naming_info() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Any ,A_ : List[Any] ) -> int: if len(A_ ) == 0: return "" A = None if any(char.isdigit() for char in word ): raise Exception(F'Parameters should not contain numbers: \'{word}\' contains a number' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 ,len(A_ ) + 1 ): A = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: A = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(A_ : Optional[Any] ): A = '' while integer != 0: A = chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s A = 0 while True: A = word + '#' + int_to_alphabetic(A_ ) if sword in info["reverse_short_word"]: continue else: A = sword break A = short_word A = word return short_word @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[Any] ,A_ : Union[str, Any] ) -> Union[str, Any]: A = param_name.split('_' ) A = [TrialShortNamer.shortname_for_word(A_ ,A_ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name A = ['', '_'] for separator in separators: A = separator.join(A_ ) if shortname not in info["reverse_short_param"]: A = shortname A = param_name return shortname return param_name @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[Any] ,A_ : Any ) -> Tuple: A = TrialShortNamer.shortname_for_key(A_ ,A_ ) A = short_name A = param_name @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ) -> List[Any]: if cls.NAMING_INFO is not None: return A = { 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } A = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(A_ ,A_ ) A = info @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,A_ : Union[str, Any] ) -> Union[str, Any]: cls.build_naming_info() assert cls.PREFIX is not None A = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F'You should provide a default value for the param name {k} with value {v}' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue A = cls.NAMING_INFO['short_param'][k] if isinstance(A_ ,A_ ): A = 1 if v else 0 A = '' if isinstance(A_ ,(int, float) ) else '-' A = F'{key}{sep}{v}' name.append(A_ ) return "_".join(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,A_ : Any ) -> int: A = repr[len(cls.PREFIX ) + 1 :] if repr == "": A = [] else: A = repr.split('_' ) A = {} for value in values: if "-" in value: A , A = value.split('-' ) else: A = re.sub('[0-9.]' ,'' ,A_ ) A = float(re.sub('[^0-9.]' ,'' ,A_ ) ) A = cls.NAMING_INFO['reverse_short_param'][p_k] A = p_v for k in cls.DEFAULTS: if k not in parameters: A = cls.DEFAULTS[k] return parameters
91
0
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "vocab_file": "vocab.json", "tokenizer_config_file": "tokenizer_config.json", "merges_file": "merges.txt", } UpperCAmelCase__ = { "vocab_file": { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json" ), }, "tokenizer_config_file": { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json" ), }, "merges_file": { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt" ), }, } UpperCAmelCase__ = "</w>" UpperCAmelCase__ = "@@ " def _a ( a :Tuple ) -> Dict: a = set() a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) a = char return pairs # Speech2Text2 has no max input length UpperCAmelCase__ = {"facebook/s2t-wav2vec2-large-en-de": 1024} class lowercase_ ( _lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['''input_ids''', '''attention_mask'''] def __init__( self : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : str="<s>" , __UpperCAmelCase : Optional[int]="<pad>" , __UpperCAmelCase : List[str]="</s>" , __UpperCAmelCase : List[Any]="<unk>" , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : int=None , **__UpperCAmelCase : Union[str, Any] , ) ->Optional[int]: """simple docstring""" super().__init__( unk_token=A_ , bos_token=A_ , eos_token=A_ , pad_token=A_ , do_lower_case=A_ , **A_ , ) a = do_lower_case with open(A_ , encoding='''utf-8''' ) as vocab_handle: a = json.load(A_ ) a = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F"""No merges files provided. {self.__class__.__name__} can only be used for decoding.""" ) a = None a = None else: with open(A_ , encoding='''utf-8''' ) as merges_handle: a = merges_handle.read().split('''\n''' )[:-1] a = [tuple(merge.split()[:2] ) for merge in merges] a = dict(zip(A_ , range(len(A_ ) ) ) ) a = {} @property def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" return len(self.decoder ) def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] a = get_pairs(A_ ) if not pairs: return token while True: a = min(A_ , key=lambda __UpperCAmelCase : self.bpe_ranks.get(A_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break a , a = bigram a = [] a = 0 while i < len(A_ ): try: a = word.index(A_ , A_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) a = j if word[i] == first and i < len(A_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 a = tuple(A_ ) a = new_word if len(A_ ) == 1: break else: a = get_pairs(A_ ) a = ''' '''.join(A_ ) if word == "\n " + BPE_TOKEN_MERGES: a = '''\n''' + BPE_TOKEN_MERGES if word.endswith(A_ ): a = word.replace(A_ , '''''' ) a = word.replace(''' ''' , A_ ) a = word return word def __lowerCAmelCase ( self : Any , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" if self.bpe_ranks is None: raise ValueError( '''This tokenizer was instantiated without a `merges.txt` file, so''' ''' that it can only be used for decoding, not for encoding.''' '''Make sure to provide `merges.txt` file at instantiation to enable ''' '''encoding.''' ) if self.do_lower_case: a = text.lower() a = text.split() a = [] for token in text: if token: split_tokens.extend(list(self.bpe(A_ ).split(''' ''' ) ) ) return split_tokens def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str ) ->int: """simple docstring""" return self.encoder.get(A_ , self.encoder.get(self.unk_token ) ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : int ) ->str: """simple docstring""" a = self.decoder.get(A_ , self.unk_token ) return result def __lowerCAmelCase ( self : str , __UpperCAmelCase : List[str] ) ->str: """simple docstring""" a = ''' '''.join(A_ ) # make sure @@ tokens are concatenated a = ''''''.join(string.split(A_ ) ) return string def __lowerCAmelCase ( self : str , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(A_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a = os.path.join( A_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) a = os.path.join( A_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(A_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=A_ , ensure_ascii=A_ ) + '''\n''' ) a = 0 if self.bpe_ranks is None: return (vocab_file,) with open(A_ , '''w''' , encoding='''utf-8''' ) as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __UpperCAmelCase : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) a = token_index writer.write(''' '''.join(A_ ) + '''\n''' ) index += 1 return (vocab_file, merges_file)
117
"""simple docstring""" import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def _snake_case ( ): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(snake_case__ ): requests.request('GET' , 'https://huggingface.co' ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request('GET' , 'https://huggingface.co' , timeout=1.0 ) @pytest.mark.integration def _snake_case ( ): with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request('GET' , 'https://huggingface.co' ) def _snake_case ( ): with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(snake_case__ ): http_head('https://huggingface.co' )
91
0
"""simple docstring""" import inspect import unittest from transformers import MobileNetVaConfig 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, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class _UpperCAmelCase ( _lowercase ): '''simple docstring''' def __lowerCAmelCase ( self ) -> List[Any]: _UpperCAmelCase : int = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A_ , '''tf_padding''' ) ) self.parent.assertTrue(hasattr(A_ , '''depth_multiplier''' ) ) class _UpperCAmelCase : '''simple docstring''' def __init__( self , A , A=1_3 , A=3 , A=3_2 , A=0.25 , A=8 , A=True , A=1_0_2_4 , A=3_2 , A="relu6" , A=0.1 , A=0.02 , A=True , A=True , A=1_0 , A=None , ) -> List[Any]: _UpperCAmelCase : Dict = parent _UpperCAmelCase : str = batch_size _UpperCAmelCase : Dict = num_channels _UpperCAmelCase : List[Any] = image_size _UpperCAmelCase : Union[str, Any] = depth_multiplier _UpperCAmelCase : Optional[Any] = min_depth _UpperCAmelCase : List[Any] = tf_padding _UpperCAmelCase : Any = int(last_hidden_size * depth_multiplier ) _UpperCAmelCase : Optional[Any] = output_stride _UpperCAmelCase : Union[str, Any] = hidden_act _UpperCAmelCase : Optional[Any] = classifier_dropout_prob _UpperCAmelCase : Optional[Any] = use_labels _UpperCAmelCase : List[Any] = is_training _UpperCAmelCase : Dict = num_labels _UpperCAmelCase : List[Any] = initializer_range _UpperCAmelCase : Union[str, Any] = scope def __lowerCAmelCase ( self ) -> Any: _UpperCAmelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase : str = None _UpperCAmelCase : List[Any] = None if self.use_labels: _UpperCAmelCase : int = ids_tensor([self.batch_size] , self.num_labels ) _UpperCAmelCase : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) _UpperCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels, pixel_labels def __lowerCAmelCase ( self ) -> List[Any]: return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self , A , A , A , A ) -> List[Any]: _UpperCAmelCase : Tuple = MobileNetVaModel(config=A_ ) model.to(A_ ) model.eval() _UpperCAmelCase : Optional[int] = model(A_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __lowerCAmelCase ( self , A , A , A , A ) -> Tuple: _UpperCAmelCase : Dict = self.num_labels _UpperCAmelCase : Any = MobileNetVaForImageClassification(A_ ) model.to(A_ ) model.eval() _UpperCAmelCase : Union[str, Any] = model(A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self ) -> Optional[Any]: _UpperCAmelCase : Optional[Any] = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : int = config_and_inputs _UpperCAmelCase : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class _UpperCAmelCase ( _lowercase ,_lowercase ,unittest.TestCase ): '''simple docstring''' a__ =(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () a__ =( {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification} if is_torch_available() else {} ) a__ =False a__ =False a__ =False a__ =False def __lowerCAmelCase ( self ) -> str: _UpperCAmelCase : Dict = MobileNetVaModelTester(self ) _UpperCAmelCase : List[str] = MobileNetVaConfigTester(self , config_class=A_ , has_text_modality=A_ ) def __lowerCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='''MobileNetV1 does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> Union[str, Any]: pass @unittest.skip(reason='''MobileNetV1 does not support input and output embeddings''' ) def __lowerCAmelCase ( self ) -> Union[str, Any]: pass @unittest.skip(reason='''MobileNetV1 does not output attentions''' ) def __lowerCAmelCase ( self ) -> List[str]: pass def __lowerCAmelCase ( self ) -> List[Any]: _UpperCAmelCase , _UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : List[str] = model_class(A_ ) _UpperCAmelCase : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase : Any = [*signature.parameters.keys()] _UpperCAmelCase : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , A_ ) def __lowerCAmelCase ( self ) -> Tuple: _UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __lowerCAmelCase ( self ) -> List[Any]: def check_hidden_states_output(A , A , A ): _UpperCAmelCase : int = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): _UpperCAmelCase : int = model(**self._prepare_for_class(A_ , A_ ) ) _UpperCAmelCase : Dict = outputs.hidden_states _UpperCAmelCase : Dict = 2_6 self.assertEqual(len(A_ ) , A_ ) _UpperCAmelCase , _UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : Tuple = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase : Any = True check_hidden_states_output(A_ , A_ , A_ ) def __lowerCAmelCase ( self ) -> List[str]: _UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) @slow def __lowerCAmelCase ( self ) -> int: for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase : str = MobileNetVaModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def lowerCamelCase_ (): _UpperCAmelCase : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __lowerCAmelCase ( self ) -> Dict: return ( MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> str: _UpperCAmelCase : Optional[Any] = MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224''' ).to(A_ ) _UpperCAmelCase : Optional[int] = self.default_image_processor _UpperCAmelCase : Tuple = prepare_img() _UpperCAmelCase : Union[str, Any] = image_processor(images=A_ , return_tensors='''pt''' ).to(A_ ) # forward pass with torch.no_grad(): _UpperCAmelCase : Dict = model(**A_ ) # verify the logits _UpperCAmelCase : Optional[Any] = torch.Size((1, 1_0_0_1) ) self.assertEqual(outputs.logits.shape , A_ ) _UpperCAmelCase : Tuple = torch.tensor([-4.1_739, -1.1_233, 3.1_205] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1E-4 ) )
506
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[str] = BioGptTokenizer _lowerCamelCase: Tuple = False def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ) as fp: fp.write(json.dumps(A_ ) ) with open(self.merges_file ,'w' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple ) -> int: A = 'lower newer' A = 'lower newer' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = BioGptTokenizer(self.vocab_file ,self.merges_file ) A = 'lower' A = ['low', 'er</w>'] A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = tokens + ['<unk>'] A = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) A = tokenizer.encode('sequence builders' ,add_special_tokens=A_ ) A = tokenizer.encode('multi-sequence build' ,add_special_tokens=A_ ) A = tokenizer.build_inputs_with_special_tokens(A_ ) A = tokenizer.build_inputs_with_special_tokens(A_ ,A_ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
91
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig A : Dict = { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/config.json''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/config.json''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/config.json''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/config.json''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/config.json''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json''', } class a_ ( _lowercase ): a : Dict = '''albert''' def __init__( self , __UpperCamelCase=30_000 , __UpperCamelCase=128 , __UpperCamelCase=4_096 , __UpperCamelCase=12 , __UpperCamelCase=1 , __UpperCamelCase=64 , __UpperCamelCase=16_384 , __UpperCamelCase=1 , __UpperCamelCase="gelu_new" , __UpperCamelCase=0 , __UpperCamelCase=0 , __UpperCamelCase=512 , __UpperCamelCase=2 , __UpperCamelCase=0.02 , __UpperCamelCase=1E-12 , __UpperCamelCase=0.1 , __UpperCamelCase="absolute" , __UpperCamelCase=0 , __UpperCamelCase=2 , __UpperCamelCase=3 , **__UpperCamelCase , ): super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) _lowercase = vocab_size _lowercase = embedding_size _lowercase = hidden_size _lowercase = num_hidden_layers _lowercase = num_hidden_groups _lowercase = num_attention_heads _lowercase = inner_group_num _lowercase = hidden_act _lowercase = intermediate_size _lowercase = hidden_dropout_prob _lowercase = attention_probs_dropout_prob _lowercase = max_position_embeddings _lowercase = type_vocab_size _lowercase = initializer_range _lowercase = layer_norm_eps _lowercase = classifier_dropout_prob _lowercase = position_embedding_type class a_ ( _lowercase ): @property def UpperCamelCase_ ( self ): if self.task == "multiple-choice": _lowercase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowercase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
287
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers _lowercase = float('''nan''') class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[str] ,A_ : Tuple ) -> Any: A = sys.stdout A = open(A_ ,'a' ) def __getattr__( self : int ,A_ : Optional[Any] ) -> Tuple: return getattr(self.stdout ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> str: self.stdout.write(A_ ) # strip tqdm codes self.file.write(re.sub(R'^.*\r' ,'' ,A_ ,0 ,re.M ) ) def _snake_case ( snake_case__ : Optional[Any]=80 , snake_case__ : List[str]=False ): A = [] # deal with critical env vars A = ['CUDA_VISIBLE_DEVICES'] for key in env_keys: A = os.environ.get(snake_case__ , snake_case__ ) if val is not None: cmd.append(F'{key}={val}' ) # python executable (not always needed if the script is executable) A = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(snake_case__ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes A = [] A = '' while len(snake_case__ ) > 0: current_line += F'{cmd.pop(0 )} ' if len(snake_case__ ) == 0 or len(snake_case__ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(snake_case__ ) A = '' return "\\\n".join(snake_case__ ) def _snake_case ( snake_case__ : str , snake_case__ : str ): # unwrap multi-line input A = re.sub(r'[\\\n]+' , ' ' , args.base_cmd ) # remove --output_dir if any and set our own A = re.sub('--output_dir\s+[^\s]+' , '' , args.base_cmd ) args.base_cmd += F' --output_dir {output_dir}' # ensure we have --overwrite_output_dir A = re.sub('--overwrite_output_dir\s+' , '' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _snake_case ( snake_case__ : List[str] , snake_case__ : Union[str, Any] , snake_case__ : str , snake_case__ : int , snake_case__ : Optional[Any] , snake_case__ : Any , snake_case__ : List[Any] ): # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , ) A = subprocess.run(snake_case__ , capture_output=snake_case__ , text=snake_case__ ) if verbose: print('STDOUT' , result.stdout ) print('STDERR' , result.stderr ) # save the streams A = variation.replace(' ' , '-' ) with open(Path(snake_case__ ) / F'log.{prefix}.stdout.txt' , 'w' ) as f: f.write(result.stdout ) with open(Path(snake_case__ ) / F'log.{prefix}.stderr.txt' , 'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(F'{output_dir}/all_results.json' , 'r' , encoding='utf-8' ) as f: A = json.load(snake_case__ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _snake_case ( snake_case__ : str , snake_case__ : str , snake_case__ : str , snake_case__ : List[str] , snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : Dict , snake_case__ : Optional[Any] , ): A = [] A = [] A = F'{id}: {variation:<{longest_variation_len}}' A = F'{preamble}: ' A = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(snake_case__ ) , desc=snake_case__ , leave=snake_case__ ): A = process_run_single( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) A = single_run_metrics[target_metric_key] if not math.isnan(snake_case__ ): metrics.append(snake_case__ ) results.append(snake_case__ ) outcome += "✓" else: outcome += "✘" A = F'\33[2K\r{outcome}' if len(snake_case__ ) > 0: A = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} A = round(mean_metrics[target_metric_key] , 2 ) A = F'{outcome} {mean_target}' if len(snake_case__ ) > 1: results_str += F' {tuple(round(snake_case__ , 2 ) for x in results )}' print(snake_case__ ) A = variation return mean_metrics else: print(snake_case__ ) return {variation_key: variation, target_metric_key: nan} def _snake_case ( ): A = torch.cuda.get_device_properties(torch.device('cuda' ) ) return F'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n' def _snake_case ( snake_case__ : List[str] , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Union[str, Any] ): A = pd.DataFrame(snake_case__ ) A = 'variation' A = 'diff_%' A = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan A = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(snake_case__ ): # as a fallback, use the minimal value as the sentinel A = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(snake_case__ ): A = df.apply( lambda snake_case__ : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='columns' , ) # re-order columns A = [variation_key, target_metric_key, diff_key, *report_metric_keys] A = df.reindex(snake_case__ , axis='columns' ) # reorder cols # capitalize A = df.rename(str.capitalize , axis='columns' ) # make the cols as narrow as possible A = df.rename(lambda snake_case__ : c.replace('_' , '<br>' ) , axis='columns' ) A = df.rename(lambda snake_case__ : c.replace('_' , '\n' ) , axis='columns' ) A = ['', 'Copy between the cut-here-lines and paste as is to github or a forum'] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=snake_case__ , floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=snake_case__ , floatfmt='.2f' )] print('\n\n'.join(snake_case__ ) ) def _snake_case ( ): A = argparse.ArgumentParser() parser.add_argument( '--base-cmd' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Base cmd' , ) parser.add_argument( '--variations' , default=snake_case__ , type=snake_case__ , nargs='+' , required=snake_case__ , help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' , ) parser.add_argument( '--base-variation' , default=snake_case__ , type=snake_case__ , help='Baseline variation to compare to. if None the minimal target value will be used to compare against' , ) parser.add_argument( '--target-metric-key' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' , ) parser.add_argument( '--report-metric-keys' , default='' , type=snake_case__ , help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' , ) parser.add_argument( '--repeat-times' , default=1 , type=snake_case__ , help='How many times to re-run each variation - an average will be reported' , ) parser.add_argument( '--output_dir' , default='output_benchmark' , type=snake_case__ , help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' , ) parser.add_argument( '--verbose' , default=snake_case__ , action='store_true' , help='Whether to show the outputs of each run or just the benchmark progress' , ) A = parser.parse_args() A = args.output_dir Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) A = get_base_command(snake_case__ , snake_case__ ) # split each dimension into its --foo variations A = [list(map(str.strip , re.split(r'\|' , snake_case__ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty A = list(map(str.strip , map(' '.join , itertools.product(*snake_case__ ) ) ) ) A = max(len(snake_case__ ) for x in variations ) # split wanted keys A = args.report_metric_keys.split() # capture prints into a log file for convenience A = F'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(F'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(F'and this script\'s output is also piped into {report_fn}' ) A = Tee(snake_case__ ) print(F'\n*** Running {len(snake_case__ )} benchmarks:' ) print(F'Base command: {" ".join(snake_case__ )}' ) A = 'variation' A = [] for id, variation in enumerate(tqdm(snake_case__ , desc='Total completion: ' , leave=snake_case__ ) ): A = base_cmd + variation.split() results.append( process_run( id + 1 , snake_case__ , snake_case__ , snake_case__ , snake_case__ , args.target_metric_key , snake_case__ , args.repeat_times , snake_case__ , args.verbose , ) ) process_results(snake_case__ , args.target_metric_key , snake_case__ , args.base_variation , snake_case__ ) if __name__ == "__main__": main()
91
0
'''simple docstring''' from collections.abc import Iterable from typing import Generic, TypeVar UpperCAmelCase = TypeVar('_T') class __snake_case( Generic[_T] ): '''simple docstring''' def __init__( self , A_ = None ) -> None: lowerCAmelCase = list(iterable or [] ) lowerCAmelCase = [] def __len__( self ) -> int: return len(self._stacka ) + len(self._stacka ) def __repr__( self ) -> str: return f'Queue({tuple(self._stacka[::-1] + self._stacka )})' def __snake_case ( self , A_ ) -> None: self._stacka.append(A_ ) def __snake_case ( self ) -> _T: lowerCAmelCase = self._stacka.pop lowerCAmelCase = self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError("""Queue is empty""" ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
433
"""simple docstring""" import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('''>=''', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType _lowercase = get_logger(__name__) def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : List[Any] , snake_case__ : int , snake_case__ : int , snake_case__ : str=0 ): os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A = os.path.join(snake_case__ , snake_case__ ) if accelerator.process_index == 0: logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A = os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving model to {ckpt_dir}' ) A = {'model': state_dict} dist_cp.save_state_dict( state_dict=snake_case__ , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Model saved to {ckpt_dir}' ) def _snake_case ( snake_case__ : int , snake_case__ : List[str] , snake_case__ : str , snake_case__ : str , snake_case__ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(snake_case__ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( 'Set the `sync_module_states` flag to `True` so that model states are synced across processes when ' 'initializing FSDP object' ) return A = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A = ( os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) if F'{MODEL_NAME}' not in input_dir else input_dir ) logger.info(F'Loading model from {ckpt_dir}' ) A = {'model': model.state_dict()} dist_cp.load_state_dict( state_dict=snake_case__ , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , planner=DefaultLoadPlanner() , ) A = state_dict['model'] logger.info(F'Model loaded from {ckpt_dir}' ) model.load_state_dict(snake_case__ ) def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int] , snake_case__ : Optional[int] , snake_case__ : Dict , snake_case__ : List[str] , snake_case__ : Any=0 ): os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A = FSDP.optim_state_dict(snake_case__ , snake_case__ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: A = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving Optimizer state to {output_optimizer_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Optimizer state saved in {output_optimizer_file}' ) else: A = os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving Optimizer state to {ckpt_dir}' ) dist_cp.save_state_dict( state_dict={'optimizer': optim_state} , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Optimizer state saved in {ckpt_dir}' ) def _snake_case ( snake_case__ : str , snake_case__ : Optional[int] , snake_case__ : List[str] , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Optional[int]=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: A = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading Optimizer state from {input_optimizer_file}' ) A = torch.load(snake_case__ ) logger.info(F'Optimizer state loaded from {input_optimizer_file}' ) else: A = ( os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) if F'{OPTIMIZER_NAME}' not in input_dir else input_dir ) logger.info(F'Loading Optimizer from {ckpt_dir}' ) A = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key='optimizer' , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , ) A = optim_state['optimizer'] logger.info(F'Optimizer loaded from {ckpt_dir}' ) A = FSDP.optim_state_dict_to_load(snake_case__ , snake_case__ , snake_case__ ) optimizer.load_state_dict(snake_case__ )
91
0
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowerCAmelCase__ : '''simple docstring''' __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 class lowerCAmelCase__ : '''simple docstring''' def __init__( self , __lowerCamelCase) -> Union[str, Any]: _A : Optional[Any] = [[] for _ in range(A_)] _A : int = size def __getitem__( self , __lowerCamelCase) -> Iterator[Edge]: return iter(self._graph[vertex]) @property def _lowerCamelCase ( self) -> Any: return self._size def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> Tuple: if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1.") if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size).") self._graph[from_vertex].append(Edge(A_ , A_)) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase) -> int | None: _A : List[Any] = deque([start_vertex]) _A : str = [None] * self.size _A : str = 0 while queue: _A : str = queue.popleft() _A : int = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _A : int = current_distance + edge.weight _A : int = distances[edge.destination_vertex] if ( isinstance(A_ , A_) and new_distance >= dest_vertex_distance ): continue _A : Tuple = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex) else: queue.append(edge.destination_vertex) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex.") return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
503
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: str = AudioLDMPipeline _lowerCamelCase: Optional[int] = TEXT_TO_AUDIO_PARAMS _lowerCamelCase: Optional[int] = TEXT_TO_AUDIO_BATCH_PARAMS _lowerCamelCase: Optional[int] = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=(32, 64) ,class_embed_type='simple_projection' ,projection_class_embeddings_input_dim=32 ,class_embeddings_concat=A_ ,) A = DDIMScheduler( beta_start=0.0_00_85 ,beta_end=0.0_12 ,beta_schedule='scaled_linear' ,clip_sample=A_ ,set_alpha_to_one=A_ ,) torch.manual_seed(0 ) A = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=1 ,out_channels=1 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) torch.manual_seed(0 ) A = ClapTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,projection_dim=32 ,) A = ClapTextModelWithProjection(A_ ) A = RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta' ,model_max_length=77 ) A = SpeechTaHifiGanConfig( model_in_dim=8 ,sampling_rate=1_6000 ,upsample_initial_channel=16 ,upsample_rates=[2, 2] ,upsample_kernel_sizes=[4, 4] ,resblock_kernel_sizes=[3, 7] ,resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] ,normalize_before=A_ ,) A = SpeechTaHifiGan(A_ ) A = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'vocoder': vocoder, } return components def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Dict=0 ) -> str: if str(A_ ).startswith('mps' ): A = torch.manual_seed(A_ ) else: A = torch.Generator(device=A_ ).manual_seed(A_ ) A = { 'prompt': 'A hammer hitting a wooden surface', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, } return inputs def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = audioldm_pipe(**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) == 256 A = audio[:10] A = np.array( [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 3 * [inputs['prompt']] # forward A = audioldm_pipe(**A_ ) A = output.audios[0] A = self.get_dummy_inputs(A_ ) A = 3 * [inputs.pop('prompt' )] A = audioldm_pipe.tokenizer( A_ ,padding='max_length' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=A_ ,return_tensors='pt' ,) A = text_inputs['input_ids'].to(A_ ) A = audioldm_pipe.text_encoder( A_ ,) A = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state A = F.normalize(A_ ,dim=-1 ) A = prompt_embeds # forward A = audioldm_pipe(**A_ ) A = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 3 * ['this is a negative prompt'] A = negative_prompt A = 3 * [inputs['prompt']] # forward A = audioldm_pipe(**A_ ) A = output.audios[0] A = self.get_dummy_inputs(A_ ) A = 3 * [inputs.pop('prompt' )] A = [] for p in [prompt, negative_prompt]: A = audioldm_pipe.tokenizer( A_ ,padding='max_length' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=A_ ,return_tensors='pt' ,) A = text_inputs['input_ids'].to(A_ ) A = audioldm_pipe.text_encoder( A_ ,) A = text_embeds.text_embeds # additional L_2 normalization over each hidden-state A = F.normalize(A_ ,dim=-1 ) embeds.append(A_ ) A , A = embeds # forward A = audioldm_pipe(**A_ ) A = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = PNDMScheduler(skip_prk_steps=A_ ) A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 'egg cracking' A = audioldm_pipe(**A_ ,negative_prompt=A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) == 256 A = audio[:10] A = np.array( [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = PNDMScheduler(skip_prk_steps=A_ ) A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = 'A hammer hitting a wooden surface' # test num_waveforms_per_prompt=1 (default) A = audioldm_pipe(A_ ,num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts A = 2 A = audioldm_pipe([prompt] * batch_size ,num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt A = 2 A = audioldm_pipe(A_ ,num_inference_steps=2 ,num_waveforms_per_prompt=A_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts A = 2 A = audioldm_pipe( [prompt] * batch_size ,num_inference_steps=2 ,num_waveforms_per_prompt=A_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = audioldm_pipe.vocoder.config.sampling_rate A = self.get_dummy_inputs(A_ ) A = audioldm_pipe(audio_length_in_s=0.0_16 ,**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) / vocoder_sampling_rate == 0.0_16 A = audioldm_pipe(audio_length_in_s=0.0_32 ,**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) / vocoder_sampling_rate == 0.0_32 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = ['hey'] A = audioldm_pipe(A_ ,num_inference_steps=1 ) A = output.audios.shape assert audio_shape == (1, 256) A = audioldm_pipe.vocoder.config config.model_in_dim *= 2 A = SpeechTaHifiGan(A_ ).to(A_ ) A = audioldm_pipe(A_ ,num_inference_steps=1 ) A = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: self._test_inference_batch_single_identical(test_mean_pixel_difference=A_ ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() ,reason='XFormers attention is only available with CUDA and `xformers` installed' ,) def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A_ ) @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[Any] ,A_ : str="cpu" ,A_ : List[str]=torch.floataa ,A_ : str=0 ) -> List[Any]: A = torch.Generator(device=A_ ).manual_seed(A_ ) A = np.random.RandomState(A_ ).standard_normal((1, 8, 128, 16) ) A = torch.from_numpy(A_ ).to(device=A_ ,dtype=A_ ) A = { 'prompt': 'A hammer hitting a wooden surface', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 2.5, } return inputs def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_inputs(A_ ) A = 25 A = audioldm_pipe(**A_ ).audios[0] assert audio.ndim == 1 assert len(A_ ) == 8_1920 A = audio[7_7230:7_7240] A = np.array( [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15] ) A = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: A = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) A = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_inputs(A_ ) A = audioldm_pipe(**A_ ).audios[0] assert audio.ndim == 1 assert len(A_ ) == 8_1920 A = audio[2_7780:2_7790] A = np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12] ) A = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
91
0
"""simple docstring""" from math import sqrt def lowercase ( lowerCAmelCase__ : int ) -> Any: assert isinstance(snake_case__ , snake_case__ ) and ( number >= 0 ), "'number' must been an int and positive" __a = True # 0 and 1 are none primes. if number <= 1: __a = False for divisor in range(2 , int(round(sqrt(snake_case__ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __a = False break # precondition assert isinstance(snake_case__ , snake_case__ ), "'status' must been from type bool" return status def lowercase ( lowerCAmelCase__ : List[str] ) -> List[str]: assert isinstance(snake_case__ , snake_case__ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __a = list(range(2 , n + 1 ) ) __a = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(snake_case__ ) ): for j in range(i + 1 , len(snake_case__ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __a = 0 # filters actual prime numbers. __a = [x for x in begin_list if x != 0] # precondition assert isinstance(snake_case__ , snake_case__ ), "'ans' must been from type list" return ans def lowercase ( lowerCAmelCase__ : int ) -> Any: assert isinstance(snake_case__ , snake_case__ ) and (n > 2), "'N' must been an int and > 2" __a = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(snake_case__ ): ans.append(snake_case__ ) # precondition assert isinstance(snake_case__ , snake_case__ ), "'ans' must been from type list" return ans def lowercase ( lowerCAmelCase__ : str ) -> Any: assert isinstance(snake_case__ , snake_case__ ) and number >= 0, "'number' must been an int and >= 0" __a = [] # this list will be returns of the function. # potential prime number factors. __a = 2 __a = number if number == 0 or number == 1: ans.append(snake_case__ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(snake_case__ ): while quotient != 1: if is_prime(snake_case__ ) and (quotient % factor == 0): ans.append(snake_case__ ) quotient /= factor else: factor += 1 else: ans.append(snake_case__ ) # precondition assert isinstance(snake_case__ , snake_case__ ), "'ans' must been from type list" return ans def lowercase ( lowerCAmelCase__ : str ) -> str: assert isinstance(snake_case__ , snake_case__ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __a = 0 # prime factorization of 'number' __a = prime_factorization(snake_case__ ) __a = max(snake_case__ ) # precondition assert isinstance(snake_case__ , snake_case__ ), "'ans' must been from type int" return ans def lowercase ( lowerCAmelCase__ : Tuple ) -> List[str]: assert isinstance(snake_case__ , snake_case__ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __a = 0 # prime factorization of 'number' __a = prime_factorization(snake_case__ ) __a = min(snake_case__ ) # precondition assert isinstance(snake_case__ , snake_case__ ), "'ans' must been from type int" return ans def lowercase ( lowerCAmelCase__ : Any ) -> List[str]: assert isinstance(snake_case__ , snake_case__ ), "'number' must been an int" assert isinstance(number % 2 == 0 , snake_case__ ), "compare bust been from type bool" return number % 2 == 0 def lowercase ( lowerCAmelCase__ : List[str] ) -> List[str]: assert isinstance(snake_case__ , snake_case__ ), "'number' must been an int" assert isinstance(number % 2 != 0 , snake_case__ ), "compare bust been from type bool" return number % 2 != 0 def lowercase ( lowerCAmelCase__ : int ) -> Tuple: assert ( isinstance(snake_case__ , snake_case__ ) and (number > 2) and is_even(snake_case__ ) ), "'number' must been an int, even and > 2" __a = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __a = get_prime_numbers(snake_case__ ) __a = len(snake_case__ ) # run variable for while-loops. __a = 0 __a = None # exit variable. for break up the loops __a = True while i < len_pn and loop: __a = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __a = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(snake_case__ , snake_case__ ) and (len(snake_case__ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Union[str, Any] ) -> List[Any]: assert ( isinstance(snake_case__ , snake_case__ ) and isinstance(snake_case__ , snake_case__ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __a = 0 while numbera != 0: __a = numbera % numbera __a = numbera __a = rest # precondition assert isinstance(snake_case__ , snake_case__ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[str] ) -> Union[str, Any]: assert ( isinstance(snake_case__ , snake_case__ ) and isinstance(snake_case__ , snake_case__ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __a = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __a = prime_factorization(snake_case__ ) __a = prime_factorization(snake_case__ ) elif numbera == 1 or numbera == 1: __a = [] __a = [] __a = max(snake_case__ , snake_case__ ) __a = 0 __a = 0 __a = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __a = prime_fac_a.count(snake_case__ ) __a = prime_fac_a.count(snake_case__ ) for _ in range(max(snake_case__ , snake_case__ ) ): ans *= n else: __a = prime_fac_a.count(snake_case__ ) for _ in range(snake_case__ ): ans *= n done.append(snake_case__ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __a = prime_fac_a.count(snake_case__ ) for _ in range(snake_case__ ): ans *= n done.append(snake_case__ ) # precondition assert isinstance(snake_case__ , snake_case__ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def lowercase ( lowerCAmelCase__ : int ) -> Tuple: assert isinstance(snake_case__ , snake_case__ ) and (n >= 0), "'number' must been a positive int" __a = 0 __a = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(snake_case__ ): ans += 1 # precondition assert isinstance(snake_case__ , snake_case__ ) and is_prime( snake_case__ ), "'ans' must been a prime number and from type int" return ans def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : Any ) -> Dict: assert ( is_prime(snake_case__ ) and is_prime(snake_case__ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __a = p_number_a + 1 # jump to the next number __a = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(snake_case__ ): number += 1 while number < p_number_a: ans.append(snake_case__ ) number += 1 # fetch the next prime number. while not is_prime(snake_case__ ): number += 1 # precondition assert ( isinstance(snake_case__ , snake_case__ ) and ans[0] != p_number_a and ans[len(snake_case__ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def lowercase ( lowerCAmelCase__ : int ) -> Any: assert isinstance(snake_case__ , snake_case__ ) and (n >= 1), "'n' must been int and >= 1" __a = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(snake_case__ ) # precondition assert ans[0] == 1 and ans[len(snake_case__ ) - 1] == n, "Error in function getDivisiors(...)" return ans def lowercase ( lowerCAmelCase__ : Tuple ) -> int: assert isinstance(snake_case__ , snake_case__ ) and ( number > 1 ), "'number' must been an int and >= 1" __a = get_divisors(snake_case__ ) # precondition assert ( isinstance(snake_case__ , snake_case__ ) and (divisors[0] == 1) and (divisors[len(snake_case__ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[str] ) -> str: assert ( isinstance(snake_case__ , snake_case__ ) and isinstance(snake_case__ , snake_case__ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __a = gcd(abs(snake_case__ ) , abs(snake_case__ ) ) # precondition assert ( isinstance(snake_case__ , snake_case__ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def lowercase ( lowerCAmelCase__ : Any ) -> Union[str, Any]: assert isinstance(snake_case__ , snake_case__ ) and (n >= 0), "'n' must been a int and >= 0" __a = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def lowercase ( lowerCAmelCase__ : List[str] ) -> Tuple: assert isinstance(snake_case__ , snake_case__ ) and (n >= 0), "'n' must been an int and >= 0" __a = 0 __a = 1 __a = 1 # this will be return for _ in range(n - 1 ): __a = ans ans += fiba __a = tmp return ans
695
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
91
0
from __future__ import annotations UpperCamelCase = 1.6021E-19 # units = C def A ( lowercase__ : float , lowercase__ : float , lowercase__ : float , ) -> Any: if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif conductivity < 0: raise ValueError("""Conductivity cannot be negative""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative""" ) elif mobility < 0: raise ValueError("""mobility cannot be negative""" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def _snake_case ( ): A = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A = get_sagemaker_input() else: A = get_cluster_input() return config def _snake_case ( snake_case__ : Any=None ): if subparsers is not None: A = subparsers.add_parser('config' , description=snake_case__ ) else: A = argparse.ArgumentParser('Accelerate config command' , description=snake_case__ ) parser.add_argument( '--config_file' , default=snake_case__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=snake_case__ ) return parser def _snake_case ( snake_case__ : Tuple ): A = get_user_input() if args.config_file is not None: A = args.config_file else: if not os.path.isdir(snake_case__ ): os.makedirs(snake_case__ ) A = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(snake_case__ ) else: config.to_yaml_file(snake_case__ ) print(F'accelerate configuration saved at {config_file}' ) def _snake_case ( ): A = config_command_parser() A = parser.parse_args() config_command(snake_case__ ) if __name__ == "__main__": main()
91
0
"""simple docstring""" from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowercase_ ( _lowerCamelCase: int ) -> Dict: '''simple docstring''' __lowerCamelCase : List[str] = int(number**0.5 ) return number == sq * sq def lowercase_ ( _lowerCamelCase: int , _lowerCamelCase: int , _lowerCamelCase: int , _lowerCamelCase: int , _lowerCamelCase: int , _lowerCamelCase: int ) -> Dict: '''simple docstring''' __lowerCamelCase : Dict = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __lowerCamelCase : Union[str, Any] = x_den * y_den * z_den __lowerCamelCase : List[Any] = gcd(snake_case__ , snake_case__ ) top //= hcf bottom //= hcf return top, bottom def lowercase_ ( _lowerCamelCase: int = 35 ) -> int: '''simple docstring''' __lowerCamelCase : Optional[Any] = set() __lowerCamelCase : Optional[Any] = 42 __lowerCamelCase : str = Fraction(0 ) __lowerCamelCase : Optional[Any] = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __lowerCamelCase : List[str] = x_num * y_den + x_den * y_num __lowerCamelCase : str = x_den * y_den __lowerCamelCase : Dict = gcd(snake_case__ , snake_case__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __lowerCamelCase : Dict = add_three( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) unique_s.add(snake_case__ ) # n=2 __lowerCamelCase : int = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __lowerCamelCase : Tuple = x_den * x_den * y_den * y_den if is_sq(snake_case__ ) and is_sq(snake_case__ ): __lowerCamelCase : List[Any] = int(sqrt(snake_case__ ) ) __lowerCamelCase : Optional[Any] = int(sqrt(snake_case__ ) ) __lowerCamelCase : Any = gcd(snake_case__ , snake_case__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __lowerCamelCase : Optional[int] = add_three( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) unique_s.add(snake_case__ ) # n=-1 __lowerCamelCase : Any = x_num * y_num __lowerCamelCase : Any = x_den * y_num + x_num * y_den __lowerCamelCase : Dict = gcd(snake_case__ , snake_case__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __lowerCamelCase : int = add_three( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) unique_s.add(snake_case__ ) # n=2 __lowerCamelCase : List[Any] = x_num * x_num * y_num * y_num __lowerCamelCase : Optional[int] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(snake_case__ ) and is_sq(snake_case__ ): __lowerCamelCase : List[str] = int(sqrt(snake_case__ ) ) __lowerCamelCase : List[str] = int(sqrt(snake_case__ ) ) __lowerCamelCase : int = gcd(snake_case__ , snake_case__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __lowerCamelCase : Dict = add_three( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) unique_s.add(snake_case__ ) for num, den in unique_s: total += Fraction(snake_case__ , snake_case__ ) return total.denominator + total.numerator if __name__ == "__main__": print(F"""{solution() = }""")
646
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : Any ,A_ : int=13 ,A_ : str=7 ,A_ : Tuple=True ,A_ : str=True ,A_ : str=False ,A_ : List[str]=True ,A_ : str=99 ,A_ : str=32 ,A_ : Optional[int]=5 ,A_ : Optional[Any]=4 ,A_ : str=37 ,A_ : Optional[Any]="gelu" ,A_ : Union[str, Any]=0.1 ,A_ : Any=0.1 ,A_ : Optional[Any]=512 ,A_ : str=16 ,A_ : int=2 ,A_ : Optional[Any]=0.02 ,A_ : str=3 ,A_ : str=4 ,A_ : List[str]=None ,) -> str: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = scope def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: return LlamaConfig( 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : Optional[int] ,A_ : Any ,A_ : Optional[Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ) -> List[Any]: A = LlamaModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : int ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Dict ,) -> List[str]: A = True A = LlamaModel(A_ ) model.to(A_ ) model.eval() A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,) A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict ,A_ : Dict ,A_ : Tuple ,A_ : Tuple ,A_ : Dict ,) -> Union[str, Any]: A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Dict ,A_ : Any ,A_ : int ,A_ : List[str] ,A_ : Tuple ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : int ,) -> List[Any]: A = True A = True A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() # first forward pass A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,use_cache=A_ ,) A = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A = ids_tensor((self.batch_size, 3) ,config.vocab_size ) A = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and A = torch.cat([input_ids, next_tokens] ,dim=-1 ) A = torch.cat([input_mask, next_mask] ,dim=-1 ) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,past_key_values=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] # select random slice A = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A = output_from_no_past[:, -3:, random_slice_idx].detach() A = 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 _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _lowerCamelCase: List[Any] = (LlamaForCausalLM,) if is_torch_available() else () _lowerCamelCase: Any = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) _lowerCamelCase: int = False _lowerCamelCase: List[str] = False def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = LlamaModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A = type self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'single_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'multi_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ) -> str: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = ids_tensor([1, 10] ,config.vocab_size ) A = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = LlamaModel(A_ ) original_model.to(A_ ) original_model.eval() A = original_model(A_ ).last_hidden_state A = original_model(A_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = {'type': scaling_type, 'factor': 10.0} A = LlamaModel(A_ ) scaled_model.to(A_ ) scaled_model.eval() A = scaled_model(A_ ).last_hidden_state A = scaled_model(A_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' ,device_map='auto' ) A = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 A = torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) A = torch.tensor( [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # fmt: off A = torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' A = 'Simply put, the theory of relativity states that ' A = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) A = tokenizer.encode(A_ ,return_tensors='pt' ) A = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' ,device_map='sequential' ,use_safetensors=A_ ) # greedy generation outputs A = model.generate(A_ ,max_new_tokens=64 ,top_p=A_ ,temperature=1 ,do_sample=A_ ) A = tokenizer.decode(generated_ids[0] ,skip_special_tokens=A_ ) self.assertEqual(A_ ,A_ )
91
0
'''simple docstring''' from __future__ import annotations class __lowercase : def __init__( self , UpperCamelCase , UpperCamelCase ) -> int: __a , __a = text, pattern __a , __a = len(A_ ), len(A_ ) def UpperCamelCase__ ( self , UpperCamelCase ) -> int: for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def UpperCamelCase__ ( self , UpperCamelCase ) -> int: for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def UpperCamelCase__ ( self ) -> list[int]: # searches pattern in text and returns index positions __a = [] for i in range(self.textLen - self.patLen + 1 ): __a = self.mismatch_in_text(A_ ) if mismatch_index == -1: positions.append(A_ ) else: __a = self.match_in_pattern(self.text[mismatch_index] ) __a = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions UpperCAmelCase_ = "ABAABA" UpperCAmelCase_ = "AB" UpperCAmelCase_ = BoyerMooreSearch(text, pattern) UpperCAmelCase_ = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
539
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers _lowercase = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def _snake_case ( ): A = os.path.dirname(os.path.realpath(snake_case__ ) ) A = os.path.join(snake_case__ , 'words.txt' ) A = '' with open(snake_case__ ) as f: A = f.readline() A = [word.strip('"' ) for word in words.strip('\r\n' ).split(',' )] A = [ word for word in [sum(ord(snake_case__ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(snake_case__ ) if __name__ == "__main__": print(solution())
91
0
from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class _lowerCAmelCase( _lowercase ): """simple docstring""" a : Optional[Any] ='''dandelin/vilt-b32-finetuned-vqa''' a : int =( '''This is a tool that answers a question about an image. It takes an input named `image` which should be the ''' '''image containing the information, as well as a `question` which should be the question in English. It ''' '''returns a text that is the answer to the question.''' ) a : str ='''image_qa''' a : int =AutoProcessor a : Any =AutoModelForVisualQuestionAnswering a : List[Any] =['''image''', '''text'''] a : Union[str, Any] =['''text'''] def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): requires_backends(self , ['vision'] ) super().__init__(*A_ , **A_ ) def _a ( self , _lowerCamelCase , _lowerCamelCase ): return self.pre_processor(A_ , A_ , return_tensors='pt' ) def _a ( self , _lowerCamelCase ): with torch.no_grad(): return self.model(**A_ ).logits def _a ( self , _lowerCamelCase ): UpperCamelCase_: Optional[int] = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
57
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''', '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''mobilenet_v1''' def __init__( self : Optional[int] ,A_ : Optional[int]=3 ,A_ : Any=224 ,A_ : List[Any]=1.0 ,A_ : Union[str, Any]=8 ,A_ : Union[str, Any]="relu6" ,A_ : Optional[Any]=True ,A_ : List[str]=0.9_99 ,A_ : int=0.02 ,A_ : int=0.0_01 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) A = num_channels A = image_size A = depth_multiplier A = min_depth A = hidden_act A = tf_padding A = classifier_dropout_prob A = initializer_range A = layer_norm_eps class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> float: return 1e-4
91
0
class UpperCamelCase__ : def __init__(self : Union[str, Any] , snake_case_ : Union[str, Any] , snake_case_ : List[Any] ): __a : List[Any] = name __a : Optional[int] = val def __str__(self : Dict ): return f"{self.__class__.__name__}({self.name}, {self.val})" def __lt__(self : Union[str, Any] , snake_case_ : List[str] ): return self.val < other.val class UpperCamelCase__ : def __init__(self : Optional[int] , snake_case_ : Union[str, Any] ): __a : List[Any] = {} __a : List[Any] = {} __a : Union[str, Any] = self.build_heap(A_ ) def __getitem__(self : str , snake_case_ : Dict ): return self.get_value(A_ ) def lowerCAmelCase (self : int , snake_case_ : Optional[int] ): return (idx - 1) // 2 def lowerCAmelCase (self : int , snake_case_ : Tuple ): return idx * 2 + 1 def lowerCAmelCase (self : int , snake_case_ : Any ): return idx * 2 + 2 def lowerCAmelCase (self : int , snake_case_ : Tuple ): return self.heap_dict[key] def lowerCAmelCase (self : Tuple , snake_case_ : Any ): __a : Optional[int] = len(A_ ) - 1 __a : Dict = self.get_parent_idx(A_ ) for idx, i in enumerate(A_ ): __a : Optional[Any] = idx __a : Union[str, Any] = i.val for i in range(A_ , -1 , -1 ): self.sift_down(A_ , A_ ) return array def lowerCAmelCase (self : List[str] , snake_case_ : Union[str, Any] , snake_case_ : Tuple ): while True: __a : Union[str, Any] = self.get_left_child_idx(A_ ) # noqa: E741 __a : int = self.get_right_child_idx(A_ ) __a : int = idx if l < len(A_ ) and array[l] < array[idx]: __a : Optional[int] = l if r < len(A_ ) and array[r] < array[smallest]: __a : Dict = r if smallest != idx: __a , __a : int = array[smallest], array[idx] ( ( __a ) , ( __a ) , ) : str = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) __a : Tuple = smallest else: break def lowerCAmelCase (self : List[Any] , snake_case_ : Any ): __a : Tuple = self.get_parent_idx(A_ ) while p >= 0 and self.heap[p] > self.heap[idx]: __a , __a : Any = self.heap[idx], self.heap[p] __a , __a : Optional[int] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) __a : Optional[int] = p __a : List[str] = self.get_parent_idx(A_ ) def lowerCAmelCase (self : Optional[Any] ): return self.heap[0] def lowerCAmelCase (self : List[str] ): __a , __a : Any = self.heap[-1], self.heap[0] __a , __a : List[Any] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) __a : int = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def lowerCAmelCase (self : List[Any] , snake_case_ : Optional[int] ): self.heap.append(A_ ) __a : List[Any] = len(self.heap ) - 1 __a : List[str] = node.val self.sift_up(len(self.heap ) - 1 ) def lowerCAmelCase (self : Union[str, Any] ): return len(self.heap ) == 0 def lowerCAmelCase (self : int , snake_case_ : Union[str, Any] , snake_case_ : Optional[int] ): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" __a : str = new_value __a : Tuple = new_value self.sift_up(self.idx_of_element[node] ) lowercase__ =Node('R', -1) lowercase__ =Node('B', 6) lowercase__ =Node('A', 3) lowercase__ =Node('X', 1) lowercase__ =Node('E', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array lowercase__ =MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('Min Heap - before decrease key') for i in my_min_heap.heap: print(i) print('Min Heap - After decrease key of node [B -> -17]') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
521
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ElectraForCausalLM''', '''ElectraForMaskedLM''', '''ElectraForMultipleChoice''', '''ElectraForPreTraining''', '''ElectraForQuestionAnswering''', '''ElectraForSequenceClassification''', '''ElectraForTokenClassification''', '''ElectraModel''', '''ElectraPreTrainedModel''', '''load_tf_weights_in_electra''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFElectraForMaskedLM''', '''TFElectraForMultipleChoice''', '''TFElectraForPreTraining''', '''TFElectraForQuestionAnswering''', '''TFElectraForSequenceClassification''', '''TFElectraForTokenClassification''', '''TFElectraModel''', '''TFElectraPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxElectraForCausalLM''', '''FlaxElectraForMaskedLM''', '''FlaxElectraForMultipleChoice''', '''FlaxElectraForPreTraining''', '''FlaxElectraForQuestionAnswering''', '''FlaxElectraForSequenceClassification''', '''FlaxElectraForTokenClassification''', '''FlaxElectraModel''', '''FlaxElectraPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
def _a ( a :int ) -> Tuple: if num < 0: return False a = num a = 0 while num > 0: a = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
117
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal _lowercase = datasets.utils.logging.get_logger(__name__) _lowercase = ['''names''', '''prefix'''] _lowercase = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] _lowercase = ['''encoding_errors''', '''on_bad_lines'''] _lowercase = ['''date_format'''] @dataclass class lowerCAmelCase_ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCamelCase: str = "," _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[int, List[int], str]] = "infer" _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[Union[int, str, List[int], List[str]]] = None _lowerCamelCase: Optional[Union[List[int], List[str]]] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: Optional[Literal["c", "python", "pyarrow"]] = None _lowerCamelCase: Dict[Union[int, str], Callable[[Any], Any]] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: bool = False _lowerCamelCase: Optional[Union[int, List[int]]] = None _lowerCamelCase: Optional[int] = None _lowerCamelCase: Optional[Union[str, List[str]]] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: bool = True _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = "." _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = '"' _lowerCamelCase: int = 0 _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: int = 0 _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: Optional[str] = None _lowerCamelCase: int = 10000 _lowerCamelCase: Optional[datasets.Features] = None _lowerCamelCase: Optional[str] = "strict" _lowerCamelCase: Literal["error", "warn", "skip"] = "error" _lowerCamelCase: Optional[str] = None def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: if self.delimiter is not None: A = self.delimiter if self.column_names is not None: A = self.column_names @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() ,A_ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class lowerCAmelCase_ ( datasets.ArrowBasedBuilder ): '''simple docstring''' _lowerCamelCase: Any = CsvConfig def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return datasets.DatasetInfo(features=self.config.features ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Any ) -> str: if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A_ ,(str, list, tuple) ): A = data_files if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,gen_kwargs={'files': files} )] A = [] for split_name, files in data_files.items(): if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] splits.append(datasets.SplitGenerator(name=A_ ,gen_kwargs={'files': files} ) ) return splits def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : pa.Table ) -> pa.Table: if self.config.features is not None: A = self.config.features.arrow_schema if all(not require_storage_cast(A_ ) for feature in self.config.features.values() ): # cheaper cast A = pa.Table.from_arrays([pa_table[field.name] for field in schema] ,schema=A_ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A = table_cast(A_ ,A_ ) return pa_table def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ) -> List[Any]: A = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(A_ ) else object for name, dtype, feature in zip(schema.names ,schema.types ,self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(A_ ) ): A = pd.read_csv(A_ ,iterator=A_ ,dtype=A_ ,**self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(A_ ): A = pa.Table.from_pandas(A_ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A_ ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(A_ )}: {e}' ) raise
91
0
"""simple docstring""" import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _UpperCAmelCase : '''simple docstring''' @staticmethod def __lowerCAmelCase ( *A , **A ) -> List[Any]: pass @is_pipeline_test @require_vision @require_torch class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' a__ =MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def __lowerCAmelCase ( self , A , A , A ) -> Dict: _UpperCAmelCase : Union[str, Any] = pipeline( '''zero-shot-object-detection''' , model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) _UpperCAmelCase : int = [ { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], } ] return object_detector, examples def __lowerCAmelCase ( self , A , A ) -> List[Any]: _UpperCAmelCase : int = object_detector(examples[0] , threshold=0.0 ) _UpperCAmelCase : List[Any] = len(A_ ) self.assertGreater(A_ , 0 ) self.assertEqual( A_ , [ { '''score''': ANY(A_ ), '''label''': ANY(A_ ), '''box''': {'''xmin''': ANY(A_ ), '''ymin''': ANY(A_ ), '''xmax''': ANY(A_ ), '''ymax''': ANY(A_ )}, } for i in range(A_ ) ] , ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def __lowerCAmelCase ( self ) -> Dict: pass @require_torch def __lowerCAmelCase ( self ) -> Union[str, Any]: _UpperCAmelCase : Tuple = pipeline( '''zero-shot-object-detection''' , model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) _UpperCAmelCase : Tuple = object_detector( '''./tests/fixtures/tests_samples/COCO/000000039769.png''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , threshold=0.64 , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {'''score''': 0.7_235, '''label''': '''cat''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_218, '''label''': '''remote''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_184, '''label''': '''couch''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.6_748, '''label''': '''remote''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_656, '''label''': '''cat''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_614, '''label''': '''couch''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_456, '''label''': '''remote''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, {'''score''': 0.642, '''label''': '''remote''', '''box''': {'''xmin''': 6_7, '''ymin''': 2_7_4, '''xmax''': 9_3, '''ymax''': 2_9_7}}, {'''score''': 0.6_419, '''label''': '''cat''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, ] , ) _UpperCAmelCase : int = object_detector( [ { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ [ {'''score''': 0.7_235, '''label''': '''cat''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_218, '''label''': '''remote''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_184, '''label''': '''couch''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.6_748, '''label''': '''remote''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_656, '''label''': '''cat''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_614, '''label''': '''couch''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_456, '''label''': '''remote''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, {'''score''': 0.642, '''label''': '''remote''', '''box''': {'''xmin''': 6_7, '''ymin''': 2_7_4, '''xmax''': 9_3, '''ymax''': 2_9_7}}, {'''score''': 0.6_419, '''label''': '''cat''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, ] ] , ) @require_torch @slow def __lowerCAmelCase ( self ) -> Optional[int]: _UpperCAmelCase : Tuple = pipeline('''zero-shot-object-detection''' ) _UpperCAmelCase : Tuple = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {'''score''': 0.2_868, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.277, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_537, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, {'''score''': 0.1_474, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_5, '''ymin''': 7_4, '''xmax''': 3_7_1, '''ymax''': 1_8_7}}, {'''score''': 0.1_208, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_4_2, '''ymax''': 4_7_6}}, ] , ) _UpperCAmelCase : List[Any] = object_detector( [ { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, ] , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ [ {'''score''': 0.2_868, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.277, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_537, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, {'''score''': 0.1_474, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_5, '''ymin''': 7_4, '''xmax''': 3_7_1, '''ymax''': 1_8_7}}, {'''score''': 0.1_208, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_4_2, '''ymax''': 4_7_6}}, ], [ {'''score''': 0.2_868, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.277, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_537, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, {'''score''': 0.1_474, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_5, '''ymin''': 7_4, '''xmax''': 3_7_1, '''ymax''': 1_8_7}}, {'''score''': 0.1_208, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_4_2, '''ymax''': 4_7_6}}, ], ] , ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def __lowerCAmelCase ( self ) -> List[str]: pass @require_torch @slow def __lowerCAmelCase ( self ) -> List[Any]: _UpperCAmelCase : Tuple = 0.2 _UpperCAmelCase : Tuple = pipeline('''zero-shot-object-detection''' ) _UpperCAmelCase : Any = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , threshold=A_ , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {'''score''': 0.2_868, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.277, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_537, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, ] , ) @require_torch @slow def __lowerCAmelCase ( self ) -> Dict: _UpperCAmelCase : Optional[int] = 2 _UpperCAmelCase : str = pipeline('''zero-shot-object-detection''' ) _UpperCAmelCase : List[str] = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , top_k=A_ , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {'''score''': 0.2_868, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.277, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, ] , )
506
"""simple docstring""" from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Any ,A_ : Callable ,A_ : Optional[Features] = None ,A_ : str = None ,A_ : bool = False ,A_ : bool = False ,A_ : Optional[dict] = None ,A_ : Optional[int] = None ,**A_ : int ,) -> str: super().__init__( features=A_ ,cache_dir=A_ ,keep_in_memory=A_ ,streaming=A_ ,num_proc=A_ ,**A_ ,) A = Generator( cache_dir=A_ ,features=A_ ,generator=A_ ,gen_kwargs=A_ ,**A_ ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: # Build iterable dataset if self.streaming: A = self.builder.as_streaming_dataset(split='train' ) # Build regular (map-style) dataset else: A = None A = None A = None A = None self.builder.download_and_prepare( download_config=A_ ,download_mode=A_ ,verification_mode=A_ ,base_path=A_ ,num_proc=self.num_proc ,) A = self.builder.as_dataset( split='train' ,verification_mode=A_ ,in_memory=self.keep_in_memory ) return dataset
91
0
from datetime import datetime as dt import os from github import Github A : Optional[Any] = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''feature request''', '''new model''', '''wip''', ] def UpperCamelCase__ ( ) -> Dict: _lowercase = Github(os.environ["""GITHUB_TOKEN"""] ) _lowercase = g.get_repo("""huggingface/transformers""" ) _lowercase = repo.get_issues(state="""open""" ) for issue in open_issues: _lowercase = sorted([comment for comment in issue.get_comments()] , key=lambda SCREAMING_SNAKE_CASE_ : i.created_at , reverse=snake_case__ ) _lowercase = comments[0] if len(snake_case__ ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="""closed""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) if __name__ == "__main__": main()
287
"""simple docstring""" from maths.prime_check import is_prime def _snake_case ( snake_case__ : int ): if not isinstance(snake_case__ , snake_case__ ): A = F'Input value of [number={number}] must be an integer' raise TypeError(snake_case__ ) if is_prime(snake_case__ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
91
0
'''simple docstring''' import pickle import numpy as np from matplotlib import pyplot as plt class __snake_case: '''simple docstring''' def __init__( self , A_ , A_ , A_ , A_ , A_ , A_=0.2 , A_=0.2 ) -> Optional[Any]: lowerCAmelCase = bp_numa lowerCAmelCase = bp_numa lowerCAmelCase = bp_numa lowerCAmelCase = conva_get[:2] lowerCAmelCase = conva_get[2] lowerCAmelCase = size_pa lowerCAmelCase = rate_w lowerCAmelCase = rate_t lowerCAmelCase = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] lowerCAmelCase = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowerCAmelCase = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowerCAmelCase = -2 * np.random.rand(self.conva[1] ) + 1 lowerCAmelCase = -2 * np.random.rand(self.num_bpa ) + 1 lowerCAmelCase = -2 * np.random.rand(self.num_bpa ) + 1 def __snake_case ( self , A_ ) -> Optional[Any]: # save model dict with pickle lowerCAmelCase = { """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(A_ , """wb""" ) as f: pickle.dump(A_ , A_ ) print(f'Model saved: {save_path}' ) @classmethod def __snake_case ( cls , A_ ) -> Dict: # read saved model with open(A_ , """rb""" ) as f: lowerCAmelCase = pickle.load(A_ ) # noqa: S301 lowerCAmelCase = model_dic.get("""conv1""" ) conv_get.append(model_dic.get("""step_conv1""" ) ) lowerCAmelCase = model_dic.get("""size_pooling1""" ) lowerCAmelCase = model_dic.get("""num_bp1""" ) lowerCAmelCase = model_dic.get("""num_bp2""" ) lowerCAmelCase = model_dic.get("""num_bp3""" ) lowerCAmelCase = model_dic.get("""rate_weight""" ) lowerCAmelCase = model_dic.get("""rate_thre""" ) # create model instance lowerCAmelCase = CNN(A_ , A_ , A_ , A_ , A_ , A_ , A_ ) # modify model parameter lowerCAmelCase = model_dic.get("""w_conv1""" ) lowerCAmelCase = model_dic.get("""wkj""" ) lowerCAmelCase = model_dic.get("""vji""" ) lowerCAmelCase = model_dic.get("""thre_conv1""" ) lowerCAmelCase = model_dic.get("""thre_bp2""" ) lowerCAmelCase = model_dic.get("""thre_bp3""" ) return conv_ins def __snake_case ( self , A_ ) -> List[Any]: return 1 / (1 + np.exp(-1 * x )) def __snake_case ( self , A_ ) -> List[str]: return round(A_ , 3 ) def __snake_case ( self , A_ , A_ , A_ , A_ , A_ ) -> Optional[Any]: # convolution process lowerCAmelCase = convs[0] lowerCAmelCase = convs[1] lowerCAmelCase = np.shape(A_ )[0] # get the data slice of original image data, data_focus lowerCAmelCase = [] for i_focus in range(0 , size_data - size_conv + 1 , A_ ): for j_focus in range(0 , size_data - size_conv + 1 , A_ ): lowerCAmelCase = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(A_ ) # calculate the feature map of every single kernel, and saved as list of matrix lowerCAmelCase = [] lowerCAmelCase = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(A_ ): lowerCAmelCase = [] for i_focus in range(len(A_ ) ): lowerCAmelCase = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(A_ ) ) lowerCAmelCase = np.asmatrix(A_ ).reshape( A_ , A_ ) data_featuremap.append(A_ ) # expanding the data slice to One dimenssion lowerCAmelCase = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(A_ ) ) lowerCAmelCase = np.asarray(A_ ) return focus_list, data_featuremap def __snake_case ( self , A_ , A_ , A_="average_pool" ) -> List[Any]: # pooling process lowerCAmelCase = len(featuremaps[0] ) lowerCAmelCase = int(size_map / size_pooling ) lowerCAmelCase = [] for i_map in range(len(A_ ) ): lowerCAmelCase = featuremaps[i_map] lowerCAmelCase = [] for i_focus in range(0 , A_ , A_ ): for j_focus in range(0 , A_ , A_ ): lowerCAmelCase = 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(A_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(A_ ) ) lowerCAmelCase = np.asmatrix(A_ ).reshape(A_ , A_ ) featuremap_pooled.append(A_ ) return featuremap_pooled def __snake_case ( self , A_ ) -> List[str]: # expanding three dimension data to one dimension list lowerCAmelCase = [] for i in range(len(A_ ) ): lowerCAmelCase = np.shape(data[i] ) lowerCAmelCase = data[i].reshape(1 , shapes[0] * shapes[1] ) lowerCAmelCase = data_listed.getA().tolist()[0] data_expanded.extend(A_ ) lowerCAmelCase = np.asarray(A_ ) return data_expanded def __snake_case ( self , A_ ) -> Optional[Any]: # expanding matrix to one dimension list lowerCAmelCase = np.asarray(A_ ) lowerCAmelCase = np.shape(A_ ) lowerCAmelCase = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __snake_case ( self , A_ , A_ , A_ , A_ , A_ ) -> Tuple: lowerCAmelCase = [] lowerCAmelCase = 0 for i_map in range(A_ ): lowerCAmelCase = np.ones((size_map, size_map) ) for i in range(0 , A_ , A_ ): for j in range(0 , A_ , A_ ): lowerCAmelCase = pd_pool[ i_pool ] lowerCAmelCase = i_pool + 1 lowerCAmelCase = np.multiply( A_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(A_ ) return pd_all def __snake_case ( self , A_ , A_ , A_ , A_ , A_ , A_=bool ) -> Optional[Any]: # model traning print("""----------------------Start Training-------------------------""" ) print((""" - - Shape: Train_Data """, np.shape(A_ )) ) print((""" - - Shape: Teach_Data """, np.shape(A_ )) ) lowerCAmelCase = 0 lowerCAmelCase = [] lowerCAmelCase = 1_0000 while rp < n_repeat and mse >= error_accuracy: lowerCAmelCase = 0 print(f'-------------Learning Time {rp}--------------' ) for p in range(len(A_ ) ): # print('------------Learning Image: %d--------------'%p) lowerCAmelCase = np.asmatrix(datas_train[p] ) lowerCAmelCase = np.asarray(datas_teach[p] ) lowerCAmelCase, lowerCAmelCase = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowerCAmelCase = self.pooling(A_ , self.size_poolinga ) lowerCAmelCase = np.shape(A_ ) lowerCAmelCase = self._expand(A_ ) lowerCAmelCase = data_bp_input lowerCAmelCase = np.dot(A_ , self.vji.T ) - self.thre_bpa lowerCAmelCase = self.sig(A_ ) lowerCAmelCase = np.dot(A_ , self.wkj.T ) - self.thre_bpa lowerCAmelCase = self.sig(A_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- lowerCAmelCase = np.multiply( (data_teach - bp_outa) , np.multiply(A_ , (1 - bp_outa) ) ) lowerCAmelCase = np.multiply( np.dot(A_ , self.wkj ) , np.multiply(A_ , (1 - bp_outa) ) ) lowerCAmelCase = np.dot(A_ , self.vji ) lowerCAmelCase = pd_i_all / (self.size_poolinga * self.size_poolinga) lowerCAmelCase = pd_conva_pooled.T.getA().tolist() lowerCAmelCase = self._calculate_gradient_from_pool( A_ , A_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): lowerCAmelCase = self._expand_mat(pd_conva_all[k_conv] ) lowerCAmelCase = self.rate_weight * np.dot(A_ , A_ ) lowerCAmelCase = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) lowerCAmelCase = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer lowerCAmelCase = self.wkj + pd_k_all.T * bp_outa * self.rate_weight lowerCAmelCase = self.vji + pd_j_all.T * bp_outa * self.rate_weight lowerCAmelCase = self.thre_bpa - pd_k_all * self.rate_thre lowerCAmelCase = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image lowerCAmelCase = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) lowerCAmelCase = rp + 1 lowerCAmelCase = error_count / patterns all_mse.append(A_ ) def draw_error(): lowerCAmelCase = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(A_ , """+-""" ) plt.plot(A_ , """r--""" ) plt.xlabel("""Learning Times""" ) plt.ylabel("""All_mse""" ) plt.grid(A_ , alpha=0.5 ) plt.show() print("""------------------Training Complished---------------------""" ) print((""" - - Training epoch: """, rp, f' - - Mse: {mse:.6f}') ) if draw_e: draw_error() return mse def __snake_case ( self , A_ ) -> Union[str, Any]: # model predict lowerCAmelCase = [] print("""-------------------Start Testing-------------------------""" ) print((""" - - Shape: Test_Data """, np.shape(A_ )) ) for p in range(len(A_ ) ): lowerCAmelCase = np.asmatrix(datas_test[p] ) lowerCAmelCase, lowerCAmelCase = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowerCAmelCase = self.pooling(A_ , self.size_poolinga ) lowerCAmelCase = self._expand(A_ ) lowerCAmelCase = data_bp_input lowerCAmelCase = bp_outa * self.vji.T - self.thre_bpa lowerCAmelCase = self.sig(A_ ) lowerCAmelCase = bp_outa * self.wkj.T - self.thre_bpa lowerCAmelCase = self.sig(A_ ) produce_out.extend(bp_outa.getA().tolist() ) lowerCAmelCase = [list(map(self.do_round , A_ ) ) for each in produce_out] return np.asarray(A_ ) def __snake_case ( self , A_ ) -> Any: # return the data of image after convoluting process so we can check it out lowerCAmelCase = np.asmatrix(A_ ) lowerCAmelCase, lowerCAmelCase = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowerCAmelCase = self.pooling(A_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
433
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[str]=0 ) -> str: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = OnnxStableDiffusionImgaImgPipeline.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_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) 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_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.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 ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
91
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase__ = { 'configuration_bloom': ['BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BloomConfig', 'BloomOnnxConfig'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['BloomTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ 'BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST', 'BloomForCausalLM', 'BloomModel', 'BloomPreTrainedModel', 'BloomForSequenceClassification', 'BloomForTokenClassification', 'BloomForQuestionAnswering', ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
503
"""simple docstring""" from __future__ import annotations def _snake_case ( snake_case__ : tuple[int, int] , snake_case__ : int ): A , A = position A = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] A = [] for position in positions: A , A = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(snake_case__ ) return permissible_positions def _snake_case ( snake_case__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _snake_case ( snake_case__ : list[list[int]] , snake_case__ : tuple[int, int] , snake_case__ : int ): if is_complete(snake_case__ ): return True for position in get_valid_pos(snake_case__ , len(snake_case__ ) ): A , A = position if board[y][x] == 0: A = curr + 1 if open_knight_tour_helper(snake_case__ , snake_case__ , curr + 1 ): return True A = 0 return False def _snake_case ( snake_case__ : int ): A = [[0 for i in range(snake_case__ )] for j in range(snake_case__ )] for i in range(snake_case__ ): for j in range(snake_case__ ): A = 1 if open_knight_tour_helper(snake_case__ , (i, j) , 1 ): return board A = 0 A = F'Open Kight Tour cannot be performed on a board of size {n}' raise ValueError(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod()
91
0
"""simple docstring""" from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('''socket.socket''' ) @patch('''builtins.open''' ) def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : str ) -> str: # ===== initialization ===== __a = Mock() __a = conn, Mock() __a = iter([1, None] ) __a = lambda lowerCAmelCase__ : next(snake_case__ ) # ===== invoke ===== send_file(filename='''mytext.txt''' , testing=snake_case__ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
695
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Optional[int] = BlenderbotSmallTokenizer _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: super().setUp() A = ['__start__', 'adapt', 'act', 'ap@@', 'te', '__end__', '__unk__'] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['#version: 0.2', 'a p', 't e</w>', 'ap t</w>', 'a d', 'ad apt</w>', 'a c', 'ac t</w>', ''] A = {'unk_token': '__unk__', 'bos_token': '__start__', 'eos_token': '__end__'} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,**A_ : Union[str, Any] ) -> Optional[int]: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Tuple ) -> List[Any]: A = 'adapt act apte' A = 'adapt act apte' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: A = BlenderbotSmallTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) A = 'adapt act apte' A = ['adapt', 'act', 'ap@@', 'te'] A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] A = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) assert tok('sam' ).input_ids == [1384] A = 'I am a small frog.' A = tok([src_text] ,padding=A_ ,truncation=A_ )['input_ids'] A = tok.batch_decode(A_ ,skip_special_tokens=A_ ,clean_up_tokenization_spaces=A_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) A = 'I am a small frog .' A = '.' A = tok(A_ )['input_ids'] A = tok(A_ )['input_ids'] assert encoded[-1] == encoded_dot[0]
91
0
from importlib import import_module from .logging import get_logger UpperCamelCase = get_logger(__name__) class lowerCAmelCase_ : """simple docstring""" def __init__( self :Dict , lowerCamelCase__ :Tuple , lowerCamelCase__ :str=None ): UpperCamelCase__ :Tuple = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , A_ , getattr(A_ , A_ ) ) UpperCamelCase__ :Optional[int] = module._original_module if isinstance(A_ , _PatchedModuleObj ) else module class lowerCAmelCase_ : """simple docstring""" _snake_case : Union[str, Any] = [] def __init__( self :Optional[int] , lowerCamelCase__ :List[Any] , lowerCamelCase__ :str , lowerCamelCase__ :List[str] , lowerCamelCase__ :Any=None ): UpperCamelCase__ :Dict = obj UpperCamelCase__ :Dict = target UpperCamelCase__ :List[str] = new UpperCamelCase__ :Optional[Any] = target.split(""".""" )[0] UpperCamelCase__ :int = {} UpperCamelCase__ :Dict = attrs or [] def __enter__( self :Optional[int] ): *UpperCamelCase__ , UpperCamelCase__ :int = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(A_ ) ): try: UpperCamelCase__ :Optional[Any] = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCamelCase__ :List[str] = getattr(self.obj , A_ ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(A_ , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCamelCase__ :Any = obj_attr # patch at top level setattr(self.obj , A_ , _PatchedModuleObj(A_ , attrs=self.attrs ) ) UpperCamelCase__ :Dict = getattr(self.obj , A_ ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(A_ , A_ , _PatchedModuleObj(getattr(A_ , A_ , A_ ) , attrs=self.attrs ) ) UpperCamelCase__ :List[str] = getattr(A_ , A_ ) # finally set the target attribute setattr(A_ , A_ , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCamelCase__ :int = getattr(import_module(""".""".join(A_ ) ) , A_ ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , A_ ) is attr_value: UpperCamelCase__ :List[Any] = getattr(self.obj , A_ ) setattr(self.obj , A_ , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCamelCase__ :List[Any] = globals()["""__builtins__"""][target_attr] setattr(self.obj , A_ , self.new ) else: raise RuntimeError(f"""Tried to patch attribute {target_attr} instead of a submodule.""" ) def __exit__( self :Optional[int] , *lowerCamelCase__ :Optional[int] ): for attr in list(self.original ): setattr(self.obj , A_ , self.original.pop(A_ ) ) def __a ( self :int ): self.__enter__() self._active_patches.append(self ) def __a ( self :str ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
45
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''image_processor''', '''tokenizer'''] _lowerCamelCase: Optional[int] = '''Pix2StructImageProcessor''' _lowerCamelCase: Dict = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : Optional[int] ,A_ : List[str] ,A_ : Optional[int] ) -> int: A = False super().__init__(A_ ,A_ ) def __call__( self : Any ,A_ : List[str]=None ,A_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,A_ : bool = True ,A_ : Union[bool, str, PaddingStrategy] = False ,A_ : Union[bool, str, TruncationStrategy] = None ,A_ : Optional[int] = None ,A_ : Optional[int] = 2048 ,A_ : int = 0 ,A_ : Optional[int] = None ,A_ : Optional[bool] = None ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = True ,A_ : Optional[Union[str, TensorType]] = None ,**A_ : Tuple ,) -> BatchEncoding: if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None and not self.image_processor.is_vqa: A = self.tokenizer A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,**A_ ) else: # add pixel_values and bbox A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,header_text=A_ ,**A_ ) if text is not None and not self.image_processor.is_vqa: A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) if "attention_mask" in text_encoding: A = text_encoding.pop('attention_mask' ) if "input_ids" in text_encoding: A = text_encoding.pop('input_ids' ) else: A = None if text_encoding is not None: encoding_image_processor.update(A_ ) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,*A_ : Optional[Any] ,**A_ : Dict ) -> Union[str, Any]: return self.tokenizer.batch_decode(*A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,*A_ : Tuple ,**A_ : List[str] ) -> Any: return self.tokenizer.decode(*A_ ,**A_ ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: A = self.tokenizer.model_input_names A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
91
0
"""simple docstring""" class _snake_case : def __init__( self : int , UpperCAmelCase : int ): __lowerCamelCase : str = size __lowerCamelCase : Any = [0] * size __lowerCamelCase : List[Any] = [0] * size @staticmethod def lowerCamelCase__ ( UpperCAmelCase : int ): return index | (index + 1) @staticmethod def lowerCamelCase__ ( UpperCAmelCase : int ): return (index & (index + 1)) - 1 def lowerCamelCase__ ( self : Optional[Any] , UpperCAmelCase : int , UpperCAmelCase : int ): __lowerCamelCase : Tuple = value while index < self.size: __lowerCamelCase : Any = self.get_prev(A_ ) + 1 if current_left_border == index: __lowerCamelCase : int = value else: __lowerCamelCase : List[Any] = max(A_ , A_ , A_ ) __lowerCamelCase : Optional[int] = self.get_next(A_ ) def lowerCamelCase__ ( self : List[str] , UpperCAmelCase : int , UpperCAmelCase : int ): right -= 1 # Because of right is exclusive __lowerCamelCase : str = 0 while left <= right: __lowerCamelCase : Dict = self.get_prev(A_ ) if left <= current_left: __lowerCamelCase : str = max(A_ , self.tree[right] ) __lowerCamelCase : Optional[int] = current_left else: __lowerCamelCase : Dict = max(A_ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
646
"""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 _lowercase = logging.get_logger(__name__) _lowercase = '''▁''' _lowercase = {'''vocab_file''': '''sentencepiece.bpe.model'''} _lowercase = { '''vocab_file''': { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model''' ), } } _lowercase = { '''xlm-roberta-base''': 5_12, '''xlm-roberta-large''': 5_12, '''xlm-roberta-large-finetuned-conll02-dutch''': 5_12, '''xlm-roberta-large-finetuned-conll02-spanish''': 5_12, '''xlm-roberta-large-finetuned-conll03-english''': 5_12, '''xlm-roberta-large-finetuned-conll03-german''': 5_12, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[str] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] ,A_ : str ,A_ : str="<s>" ,A_ : Any="</s>" ,A_ : Tuple="</s>" ,A_ : Any="<s>" ,A_ : Optional[Any]="<unk>" ,A_ : int="<pad>" ,A_ : str="<mask>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : Optional[int] ,) -> None: # Mask token behave like a normal word, i.e. include the space before it A = AddedToken(A_ ,lstrip=A_ ,rstrip=A_ ) if isinstance(A_ ,A_ ) else mask_token A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,sep_token=A_ ,cls_token=A_ ,pad_token=A_ ,mask_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) A = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token A = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab A = 1 A = len(self.sp_model ) + self.fairseq_offset A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ) -> Any: A = self.__dict__.copy() A = None A = self.sp_model.serialized_model_proto() return state def __setstate__( self : str ,A_ : str ) -> Optional[Any]: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A = [self.cls_token_id] A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: A = [self.sep_token_id] A = [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 _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[Any] ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] A = self.sp_model.PieceToId(A_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> int: 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 _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = ''.join(A_ ).replace(A_ ,' ' ).strip() return out_string def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
91
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor UpperCAmelCase_ = logging.get_logger(__name__) class __lowercase ( _lowercase ): def __init__( self , *UpperCamelCase , **UpperCamelCase ) -> None: warnings.warn( 'The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use DeformableDetrImageProcessor instead.' , A_ , ) super().__init__(*A_ , **A_ )
539
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
def snake_case (UpperCAmelCase__ = 1_0_0_0 ) -> Any: UpperCamelCase_: int = 2**power UpperCamelCase_: Optional[Any] = 0 while n: UpperCamelCase_ ,UpperCamelCase_: Tuple = r + n % 1_0, n // 1_0 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
57
"""simple docstring""" from torch import nn def _snake_case ( snake_case__ : Union[str, Any] ): 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}' )
91
0
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCamelCase__ ( _lowercase ): def __init__(self : Any , snake_case_ : Callable , snake_case_ : Optional[Features] = None , snake_case_ : str = None , snake_case_ : bool = False , snake_case_ : bool = False , snake_case_ : Optional[dict] = None , snake_case_ : Optional[int] = None , **snake_case_ : int , ): super().__init__( features=A_ , cache_dir=A_ , keep_in_memory=A_ , streaming=A_ , num_proc=A_ , **A_ , ) __a : Any = Generator( cache_dir=A_ , features=A_ , generator=A_ , gen_kwargs=A_ , **A_ , ) def lowerCAmelCase (self : Optional[int] ): # Build iterable dataset if self.streaming: __a : int = self.builder.as_streaming_dataset(split='''train''' ) # Build regular (map-style) dataset else: __a : int = None __a : Optional[Any] = None __a : Optional[Any] = None __a : Tuple = None self.builder.download_and_prepare( download_config=A_ , download_mode=A_ , verification_mode=A_ , base_path=A_ , num_proc=self.num_proc , ) __a : int = self.builder.as_dataset( split='''train''' , verification_mode=A_ , in_memory=self.keep_in_memory ) return dataset
521
"""simple docstring""" import copy import re class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str = '''hp''' _lowerCamelCase: List[Any] = {} _lowerCamelCase: List[Any] = None @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,A_ : List[str] ,A_ : Optional[Any] ) -> Tuple: A = prefix A = defaults cls.build_naming_info() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Any ,A_ : List[Any] ) -> int: if len(A_ ) == 0: return "" A = None if any(char.isdigit() for char in word ): raise Exception(F'Parameters should not contain numbers: \'{word}\' contains a number' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 ,len(A_ ) + 1 ): A = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: A = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(A_ : Optional[Any] ): A = '' while integer != 0: A = chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s A = 0 while True: A = word + '#' + int_to_alphabetic(A_ ) if sword in info["reverse_short_word"]: continue else: A = sword break A = short_word A = word return short_word @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[Any] ,A_ : Union[str, Any] ) -> Union[str, Any]: A = param_name.split('_' ) A = [TrialShortNamer.shortname_for_word(A_ ,A_ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name A = ['', '_'] for separator in separators: A = separator.join(A_ ) if shortname not in info["reverse_short_param"]: A = shortname A = param_name return shortname return param_name @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[Any] ,A_ : Any ) -> Tuple: A = TrialShortNamer.shortname_for_key(A_ ,A_ ) A = short_name A = param_name @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ) -> List[Any]: if cls.NAMING_INFO is not None: return A = { 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } A = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(A_ ,A_ ) A = info @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,A_ : Union[str, Any] ) -> Union[str, Any]: cls.build_naming_info() assert cls.PREFIX is not None A = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F'You should provide a default value for the param name {k} with value {v}' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue A = cls.NAMING_INFO['short_param'][k] if isinstance(A_ ,A_ ): A = 1 if v else 0 A = '' if isinstance(A_ ,(int, float) ) else '-' A = F'{key}{sep}{v}' name.append(A_ ) return "_".join(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,A_ : Any ) -> int: A = repr[len(cls.PREFIX ) + 1 :] if repr == "": A = [] else: A = repr.split('_' ) A = {} for value in values: if "-" in value: A , A = value.split('-' ) else: A = re.sub('[0-9.]' ,'' ,A_ ) A = float(re.sub('[^0-9.]' ,'' ,A_ ) ) A = cls.NAMING_INFO['reverse_short_param'][p_k] A = p_v for k in cls.DEFAULTS: if k not in parameters: A = cls.DEFAULTS[k] return parameters
91
0
def _a ( a :List[str] , a :Optional[int] ) -> Union[str, Any]: # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) a = (boundary[1] - boundary[0]) / steps a = boundary[0] a = boundary[1] a = make_points(snake_case__ , snake_case__ , snake_case__ ) a = 0.0 y += (h / 2.0) * f(snake_case__ ) for i in x_i: # print(i) y += h * f(snake_case__ ) y += (h / 2.0) * f(snake_case__ ) return y def _a ( a :Any , a :List[Any] , a :Any ) -> Tuple: a = a + h while x < (b - h): yield x a = x + h def _a ( a :Optional[Any] ) -> List[str]: # enter your function here a = (x - 0) * (x - 0) return y def _a ( ) -> Optional[Any]: a = 0.0 # Lower bound of integration a = 1.0 # Upper bound of integration a = 10.0 # define number of steps or resolution a = [a, b] # define boundary of integration a = method_a(snake_case__ , snake_case__ ) print(F"""y = {y}""" ) if __name__ == "__main__": main()
117
"""simple docstring""" import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def _snake_case ( ): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(snake_case__ ): requests.request('GET' , 'https://huggingface.co' ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request('GET' , 'https://huggingface.co' , timeout=1.0 ) @pytest.mark.integration def _snake_case ( ): with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request('GET' , 'https://huggingface.co' ) def _snake_case ( ): with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(snake_case__ ): http_head('https://huggingface.co' )
91
0
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class _UpperCAmelCase ( _lowercase ,unittest.TestCase ): '''simple docstring''' a__ =BioGptTokenizer a__ =False def __lowerCAmelCase ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _UpperCAmelCase : int = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] _UpperCAmelCase : Optional[Any] = dict(zip(A_ , range(len(A_ ) ) ) ) _UpperCAmelCase : List[Any] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] _UpperCAmelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _UpperCAmelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(A_ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(A_ ) ) def __lowerCAmelCase ( self , A ) -> int: _UpperCAmelCase : int = '''lower newer''' _UpperCAmelCase : Tuple = '''lower newer''' return input_text, output_text def __lowerCAmelCase ( self ) -> Any: _UpperCAmelCase : Union[str, Any] = BioGptTokenizer(self.vocab_file , self.merges_file ) _UpperCAmelCase : Any = '''lower''' _UpperCAmelCase : Optional[int] = ['''low''', '''er</w>'''] _UpperCAmelCase : Union[str, Any] = tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) _UpperCAmelCase : Union[str, Any] = tokens + ['''<unk>'''] _UpperCAmelCase : List[str] = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) @slow def __lowerCAmelCase ( self ) -> Optional[Any]: _UpperCAmelCase : List[str] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) _UpperCAmelCase : Optional[int] = tokenizer.encode('''sequence builders''' , add_special_tokens=A_ ) _UpperCAmelCase : List[Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=A_ ) _UpperCAmelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(A_ ) _UpperCAmelCase : int = tokenizer.build_inputs_with_special_tokens(A_ , A_ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
506
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[str] = BioGptTokenizer _lowerCamelCase: Tuple = False def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ) as fp: fp.write(json.dumps(A_ ) ) with open(self.merges_file ,'w' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple ) -> int: A = 'lower newer' A = 'lower newer' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = BioGptTokenizer(self.vocab_file ,self.merges_file ) A = 'lower' A = ['low', 'er</w>'] A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = tokens + ['<unk>'] A = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) A = tokenizer.encode('sequence builders' ,add_special_tokens=A_ ) A = tokenizer.encode('multi-sequence build' ,add_special_tokens=A_ ) A = tokenizer.build_inputs_with_special_tokens(A_ ) A = tokenizer.build_inputs_with_special_tokens(A_ ,A_ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
91
0
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : list ) -> List[Any]: _lowercase = len(snake_case__ ) for i in range(1 , snake_case__ ): _lowercase = collection[i] _lowercase = 0 _lowercase = i - 1 while low <= high: _lowercase = (low + high) // 2 if val < collection[mid]: _lowercase = mid - 1 else: _lowercase = mid + 1 for j in range(snake_case__ , snake_case__ , -1 ): _lowercase = collection[j - 1] _lowercase = val return collection if __name__ == "__main__": A : Tuple = input('''Enter numbers separated by a comma:\n''').strip() A : List[str] = [int(item) for item in user_input.split(''',''')] print(binary_insertion_sort(unsorted))
287
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers _lowercase = float('''nan''') class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[str] ,A_ : Tuple ) -> Any: A = sys.stdout A = open(A_ ,'a' ) def __getattr__( self : int ,A_ : Optional[Any] ) -> Tuple: return getattr(self.stdout ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> str: self.stdout.write(A_ ) # strip tqdm codes self.file.write(re.sub(R'^.*\r' ,'' ,A_ ,0 ,re.M ) ) def _snake_case ( snake_case__ : Optional[Any]=80 , snake_case__ : List[str]=False ): A = [] # deal with critical env vars A = ['CUDA_VISIBLE_DEVICES'] for key in env_keys: A = os.environ.get(snake_case__ , snake_case__ ) if val is not None: cmd.append(F'{key}={val}' ) # python executable (not always needed if the script is executable) A = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(snake_case__ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes A = [] A = '' while len(snake_case__ ) > 0: current_line += F'{cmd.pop(0 )} ' if len(snake_case__ ) == 0 or len(snake_case__ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(snake_case__ ) A = '' return "\\\n".join(snake_case__ ) def _snake_case ( snake_case__ : str , snake_case__ : str ): # unwrap multi-line input A = re.sub(r'[\\\n]+' , ' ' , args.base_cmd ) # remove --output_dir if any and set our own A = re.sub('--output_dir\s+[^\s]+' , '' , args.base_cmd ) args.base_cmd += F' --output_dir {output_dir}' # ensure we have --overwrite_output_dir A = re.sub('--overwrite_output_dir\s+' , '' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _snake_case ( snake_case__ : List[str] , snake_case__ : Union[str, Any] , snake_case__ : str , snake_case__ : int , snake_case__ : Optional[Any] , snake_case__ : Any , snake_case__ : List[Any] ): # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , ) A = subprocess.run(snake_case__ , capture_output=snake_case__ , text=snake_case__ ) if verbose: print('STDOUT' , result.stdout ) print('STDERR' , result.stderr ) # save the streams A = variation.replace(' ' , '-' ) with open(Path(snake_case__ ) / F'log.{prefix}.stdout.txt' , 'w' ) as f: f.write(result.stdout ) with open(Path(snake_case__ ) / F'log.{prefix}.stderr.txt' , 'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(F'{output_dir}/all_results.json' , 'r' , encoding='utf-8' ) as f: A = json.load(snake_case__ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _snake_case ( snake_case__ : str , snake_case__ : str , snake_case__ : str , snake_case__ : List[str] , snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : Dict , snake_case__ : Optional[Any] , ): A = [] A = [] A = F'{id}: {variation:<{longest_variation_len}}' A = F'{preamble}: ' A = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(snake_case__ ) , desc=snake_case__ , leave=snake_case__ ): A = process_run_single( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) A = single_run_metrics[target_metric_key] if not math.isnan(snake_case__ ): metrics.append(snake_case__ ) results.append(snake_case__ ) outcome += "✓" else: outcome += "✘" A = F'\33[2K\r{outcome}' if len(snake_case__ ) > 0: A = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} A = round(mean_metrics[target_metric_key] , 2 ) A = F'{outcome} {mean_target}' if len(snake_case__ ) > 1: results_str += F' {tuple(round(snake_case__ , 2 ) for x in results )}' print(snake_case__ ) A = variation return mean_metrics else: print(snake_case__ ) return {variation_key: variation, target_metric_key: nan} def _snake_case ( ): A = torch.cuda.get_device_properties(torch.device('cuda' ) ) return F'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n' def _snake_case ( snake_case__ : List[str] , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Union[str, Any] ): A = pd.DataFrame(snake_case__ ) A = 'variation' A = 'diff_%' A = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan A = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(snake_case__ ): # as a fallback, use the minimal value as the sentinel A = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(snake_case__ ): A = df.apply( lambda snake_case__ : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='columns' , ) # re-order columns A = [variation_key, target_metric_key, diff_key, *report_metric_keys] A = df.reindex(snake_case__ , axis='columns' ) # reorder cols # capitalize A = df.rename(str.capitalize , axis='columns' ) # make the cols as narrow as possible A = df.rename(lambda snake_case__ : c.replace('_' , '<br>' ) , axis='columns' ) A = df.rename(lambda snake_case__ : c.replace('_' , '\n' ) , axis='columns' ) A = ['', 'Copy between the cut-here-lines and paste as is to github or a forum'] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=snake_case__ , floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=snake_case__ , floatfmt='.2f' )] print('\n\n'.join(snake_case__ ) ) def _snake_case ( ): A = argparse.ArgumentParser() parser.add_argument( '--base-cmd' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Base cmd' , ) parser.add_argument( '--variations' , default=snake_case__ , type=snake_case__ , nargs='+' , required=snake_case__ , help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' , ) parser.add_argument( '--base-variation' , default=snake_case__ , type=snake_case__ , help='Baseline variation to compare to. if None the minimal target value will be used to compare against' , ) parser.add_argument( '--target-metric-key' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' , ) parser.add_argument( '--report-metric-keys' , default='' , type=snake_case__ , help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' , ) parser.add_argument( '--repeat-times' , default=1 , type=snake_case__ , help='How many times to re-run each variation - an average will be reported' , ) parser.add_argument( '--output_dir' , default='output_benchmark' , type=snake_case__ , help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' , ) parser.add_argument( '--verbose' , default=snake_case__ , action='store_true' , help='Whether to show the outputs of each run or just the benchmark progress' , ) A = parser.parse_args() A = args.output_dir Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) A = get_base_command(snake_case__ , snake_case__ ) # split each dimension into its --foo variations A = [list(map(str.strip , re.split(r'\|' , snake_case__ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty A = list(map(str.strip , map(' '.join , itertools.product(*snake_case__ ) ) ) ) A = max(len(snake_case__ ) for x in variations ) # split wanted keys A = args.report_metric_keys.split() # capture prints into a log file for convenience A = F'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(F'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(F'and this script\'s output is also piped into {report_fn}' ) A = Tee(snake_case__ ) print(F'\n*** Running {len(snake_case__ )} benchmarks:' ) print(F'Base command: {" ".join(snake_case__ )}' ) A = 'variation' A = [] for id, variation in enumerate(tqdm(snake_case__ , desc='Total completion: ' , leave=snake_case__ ) ): A = base_cmd + variation.split() results.append( process_run( id + 1 , snake_case__ , snake_case__ , snake_case__ , snake_case__ , args.target_metric_key , snake_case__ , args.repeat_times , snake_case__ , args.verbose , ) ) process_results(snake_case__ , args.target_metric_key , snake_case__ , args.base_variation , snake_case__ ) if __name__ == "__main__": main()
91
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available UpperCAmelCase = {'tokenization_herbert': ['HerbertTokenizer']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ['HerbertTokenizerFast'] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
433
"""simple docstring""" import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('''>=''', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType _lowercase = get_logger(__name__) def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : List[Any] , snake_case__ : int , snake_case__ : int , snake_case__ : str=0 ): os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A = os.path.join(snake_case__ , snake_case__ ) if accelerator.process_index == 0: logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A = os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving model to {ckpt_dir}' ) A = {'model': state_dict} dist_cp.save_state_dict( state_dict=snake_case__ , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Model saved to {ckpt_dir}' ) def _snake_case ( snake_case__ : int , snake_case__ : List[str] , snake_case__ : str , snake_case__ : str , snake_case__ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(snake_case__ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( 'Set the `sync_module_states` flag to `True` so that model states are synced across processes when ' 'initializing FSDP object' ) return A = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A = ( os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) if F'{MODEL_NAME}' not in input_dir else input_dir ) logger.info(F'Loading model from {ckpt_dir}' ) A = {'model': model.state_dict()} dist_cp.load_state_dict( state_dict=snake_case__ , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , planner=DefaultLoadPlanner() , ) A = state_dict['model'] logger.info(F'Model loaded from {ckpt_dir}' ) model.load_state_dict(snake_case__ ) def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int] , snake_case__ : Optional[int] , snake_case__ : Dict , snake_case__ : List[str] , snake_case__ : Any=0 ): os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A = FSDP.optim_state_dict(snake_case__ , snake_case__ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: A = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving Optimizer state to {output_optimizer_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Optimizer state saved in {output_optimizer_file}' ) else: A = os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving Optimizer state to {ckpt_dir}' ) dist_cp.save_state_dict( state_dict={'optimizer': optim_state} , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Optimizer state saved in {ckpt_dir}' ) def _snake_case ( snake_case__ : str , snake_case__ : Optional[int] , snake_case__ : List[str] , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Optional[int]=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: A = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading Optimizer state from {input_optimizer_file}' ) A = torch.load(snake_case__ ) logger.info(F'Optimizer state loaded from {input_optimizer_file}' ) else: A = ( os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) if F'{OPTIMIZER_NAME}' not in input_dir else input_dir ) logger.info(F'Loading Optimizer from {ckpt_dir}' ) A = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key='optimizer' , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , ) A = optim_state['optimizer'] logger.info(F'Optimizer loaded from {ckpt_dir}' ) A = FSDP.optim_state_dict_to_load(snake_case__ , snake_case__ , snake_case__ ) optimizer.load_state_dict(snake_case__ )
91
0
import os import platform import sys lowerCAmelCase__ = '3' print('Python version:', sys.version) print('OS platform:', platform.platform()) print('OS architecture:', platform.machine()) try: import torch print('Torch version:', torch.__version__) print('Cuda available:', torch.cuda.is_available()) print('Cuda version:', torch.version.cuda) print('CuDNN version:', torch.backends.cudnn.version()) print('Number of GPUs available:', torch.cuda.device_count()) except ImportError: print('Torch version:', None) try: import transformers print('transformers version:', transformers.__version__) except ImportError: print('transformers version:', None)
503
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: str = AudioLDMPipeline _lowerCamelCase: Optional[int] = TEXT_TO_AUDIO_PARAMS _lowerCamelCase: Optional[int] = TEXT_TO_AUDIO_BATCH_PARAMS _lowerCamelCase: Optional[int] = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=(32, 64) ,class_embed_type='simple_projection' ,projection_class_embeddings_input_dim=32 ,class_embeddings_concat=A_ ,) A = DDIMScheduler( beta_start=0.0_00_85 ,beta_end=0.0_12 ,beta_schedule='scaled_linear' ,clip_sample=A_ ,set_alpha_to_one=A_ ,) torch.manual_seed(0 ) A = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=1 ,out_channels=1 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) torch.manual_seed(0 ) A = ClapTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,projection_dim=32 ,) A = ClapTextModelWithProjection(A_ ) A = RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta' ,model_max_length=77 ) A = SpeechTaHifiGanConfig( model_in_dim=8 ,sampling_rate=1_6000 ,upsample_initial_channel=16 ,upsample_rates=[2, 2] ,upsample_kernel_sizes=[4, 4] ,resblock_kernel_sizes=[3, 7] ,resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] ,normalize_before=A_ ,) A = SpeechTaHifiGan(A_ ) A = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'vocoder': vocoder, } return components def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Dict=0 ) -> str: if str(A_ ).startswith('mps' ): A = torch.manual_seed(A_ ) else: A = torch.Generator(device=A_ ).manual_seed(A_ ) A = { 'prompt': 'A hammer hitting a wooden surface', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, } return inputs def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = audioldm_pipe(**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) == 256 A = audio[:10] A = np.array( [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 3 * [inputs['prompt']] # forward A = audioldm_pipe(**A_ ) A = output.audios[0] A = self.get_dummy_inputs(A_ ) A = 3 * [inputs.pop('prompt' )] A = audioldm_pipe.tokenizer( A_ ,padding='max_length' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=A_ ,return_tensors='pt' ,) A = text_inputs['input_ids'].to(A_ ) A = audioldm_pipe.text_encoder( A_ ,) A = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state A = F.normalize(A_ ,dim=-1 ) A = prompt_embeds # forward A = audioldm_pipe(**A_ ) A = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 3 * ['this is a negative prompt'] A = negative_prompt A = 3 * [inputs['prompt']] # forward A = audioldm_pipe(**A_ ) A = output.audios[0] A = self.get_dummy_inputs(A_ ) A = 3 * [inputs.pop('prompt' )] A = [] for p in [prompt, negative_prompt]: A = audioldm_pipe.tokenizer( A_ ,padding='max_length' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=A_ ,return_tensors='pt' ,) A = text_inputs['input_ids'].to(A_ ) A = audioldm_pipe.text_encoder( A_ ,) A = text_embeds.text_embeds # additional L_2 normalization over each hidden-state A = F.normalize(A_ ,dim=-1 ) embeds.append(A_ ) A , A = embeds # forward A = audioldm_pipe(**A_ ) A = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = PNDMScheduler(skip_prk_steps=A_ ) A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 'egg cracking' A = audioldm_pipe(**A_ ,negative_prompt=A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) == 256 A = audio[:10] A = np.array( [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = PNDMScheduler(skip_prk_steps=A_ ) A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = 'A hammer hitting a wooden surface' # test num_waveforms_per_prompt=1 (default) A = audioldm_pipe(A_ ,num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts A = 2 A = audioldm_pipe([prompt] * batch_size ,num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt A = 2 A = audioldm_pipe(A_ ,num_inference_steps=2 ,num_waveforms_per_prompt=A_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts A = 2 A = audioldm_pipe( [prompt] * batch_size ,num_inference_steps=2 ,num_waveforms_per_prompt=A_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = audioldm_pipe.vocoder.config.sampling_rate A = self.get_dummy_inputs(A_ ) A = audioldm_pipe(audio_length_in_s=0.0_16 ,**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) / vocoder_sampling_rate == 0.0_16 A = audioldm_pipe(audio_length_in_s=0.0_32 ,**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) / vocoder_sampling_rate == 0.0_32 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = ['hey'] A = audioldm_pipe(A_ ,num_inference_steps=1 ) A = output.audios.shape assert audio_shape == (1, 256) A = audioldm_pipe.vocoder.config config.model_in_dim *= 2 A = SpeechTaHifiGan(A_ ).to(A_ ) A = audioldm_pipe(A_ ,num_inference_steps=1 ) A = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: self._test_inference_batch_single_identical(test_mean_pixel_difference=A_ ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() ,reason='XFormers attention is only available with CUDA and `xformers` installed' ,) def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A_ ) @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[Any] ,A_ : str="cpu" ,A_ : List[str]=torch.floataa ,A_ : str=0 ) -> List[Any]: A = torch.Generator(device=A_ ).manual_seed(A_ ) A = np.random.RandomState(A_ ).standard_normal((1, 8, 128, 16) ) A = torch.from_numpy(A_ ).to(device=A_ ,dtype=A_ ) A = { 'prompt': 'A hammer hitting a wooden surface', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 2.5, } return inputs def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_inputs(A_ ) A = 25 A = audioldm_pipe(**A_ ).audios[0] assert audio.ndim == 1 assert len(A_ ) == 8_1920 A = audio[7_7230:7_7240] A = np.array( [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15] ) A = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: A = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) A = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_inputs(A_ ) A = audioldm_pipe(**A_ ).audios[0] assert audio.ndim == 1 assert len(A_ ) == 8_1920 A = audio[2_7780:2_7790] A = np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12] ) A = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
91
0
"""simple docstring""" import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a ): return f'''gaussian_noise_s={seed}_shape={'_'.join([str(A_ ) for s in shape] )}.npy''' def __UpperCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def __UpperCAmelCase ( self , _a=0 , _a=(4, 4, 64, 64) , _a=False ): __a = jnp.bfloataa if fpaa else jnp.floataa __a = jnp.array(load_hf_numpy(self.get_file_format(A_ , A_ ) ) , dtype=A_ ) return image def __UpperCAmelCase ( self , _a=False , _a="CompVis/stable-diffusion-v1-4" ): __a = jnp.bfloataa if fpaa else jnp.floataa __a = '''bf16''' if fpaa else None __a , __a = FlaxUNetaDConditionModel.from_pretrained( A_ , subfolder='''unet''' , dtype=A_ , revision=A_ ) return model, params def __UpperCAmelCase ( self , _a=0 , _a=(4, 77, 768) , _a=False ): __a = jnp.bfloataa if fpaa else jnp.floataa __a = jnp.array(load_hf_numpy(self.get_file_format(A_ , A_ ) ) , dtype=A_ ) return hidden_states @parameterized.expand( [ # fmt: off [83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]], [17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]], [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]], [3, 1_000, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]], # fmt: on ] ) def __UpperCAmelCase ( self , _a , _a , _a ): __a , __a = self.get_unet_model(model_id='''CompVis/stable-diffusion-v1-4''' , fpaa=A_ ) __a = self.get_latents(A_ , fpaa=A_ ) __a = self.get_encoder_hidden_states(A_ , fpaa=A_ ) __a = model.apply( {'''params''': params} , A_ , jnp.array(A_ , dtype=jnp.intaa ) , encoder_hidden_states=A_ , ).sample assert sample.shape == latents.shape __a = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) __a = jnp.array(A_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(A_ , A_ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]], [17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]], [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]], [3, 1_000, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]], # fmt: on ] ) def __UpperCAmelCase ( self , _a , _a , _a ): __a , __a = self.get_unet_model(model_id='''stabilityai/stable-diffusion-2''' , fpaa=A_ ) __a = self.get_latents(A_ , shape=(4, 4, 96, 96) , fpaa=A_ ) __a = self.get_encoder_hidden_states(A_ , shape=(4, 77, 1_024) , fpaa=A_ ) __a = model.apply( {'''params''': params} , A_ , jnp.array(A_ , dtype=jnp.intaa ) , encoder_hidden_states=A_ , ).sample assert sample.shape == latents.shape __a = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) __a = jnp.array(A_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(A_ , A_ , atol=1E-2 )
695
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
91
0
from __future__ import annotations from math import pow, sqrt def A ( lowercase__ : float , lowercase__ : float , lowercase__ : float ) -> List[Any]: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance == 0: return {"resistance": sqrt(pow(snake_case__ , 2 ) - pow(snake_case__ , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(snake_case__ , 2 ) - pow(snake_case__ , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(snake_case__ , 2 ) + pow(snake_case__ , 2 ) )} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def _snake_case ( ): A = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A = get_sagemaker_input() else: A = get_cluster_input() return config def _snake_case ( snake_case__ : Any=None ): if subparsers is not None: A = subparsers.add_parser('config' , description=snake_case__ ) else: A = argparse.ArgumentParser('Accelerate config command' , description=snake_case__ ) parser.add_argument( '--config_file' , default=snake_case__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=snake_case__ ) return parser def _snake_case ( snake_case__ : Tuple ): A = get_user_input() if args.config_file is not None: A = args.config_file else: if not os.path.isdir(snake_case__ ): os.makedirs(snake_case__ ) A = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(snake_case__ ) else: config.to_yaml_file(snake_case__ ) print(F'accelerate configuration saved at {config_file}' ) def _snake_case ( ): A = config_command_parser() A = parser.parse_args() config_command(snake_case__ ) if __name__ == "__main__": main()
91
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class _snake_case ( _lowercase ): snake_case__ = '''altclip_text_model''' def __init__( self : Tuple , UpperCAmelCase : List[str]=250002 , UpperCAmelCase : Tuple=1024 , UpperCAmelCase : Dict=24 , UpperCAmelCase : Union[str, Any]=16 , UpperCAmelCase : str=4096 , UpperCAmelCase : str="gelu" , UpperCAmelCase : List[str]=0.1 , UpperCAmelCase : Optional[int]=0.1 , UpperCAmelCase : Tuple=514 , UpperCAmelCase : int=1 , UpperCAmelCase : Union[str, Any]=0.0_2 , UpperCAmelCase : Dict=0.0_2 , UpperCAmelCase : Dict=1E-05 , UpperCAmelCase : int=1 , UpperCAmelCase : List[Any]=0 , UpperCAmelCase : Optional[Any]=2 , UpperCAmelCase : int="absolute" , UpperCAmelCase : Optional[int]=True , UpperCAmelCase : Dict=768 , **UpperCAmelCase : Tuple , ): super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : List[Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = hidden_act __lowerCamelCase : List[str] = intermediate_size __lowerCamelCase : List[Any] = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : List[Any] = type_vocab_size __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : List[str] = initializer_factor __lowerCamelCase : Dict = layer_norm_eps __lowerCamelCase : List[str] = position_embedding_type __lowerCamelCase : Dict = use_cache __lowerCamelCase : Optional[Any] = project_dim class _snake_case ( _lowercase ): snake_case__ = '''altclip_vision_model''' def __init__( self : int , UpperCAmelCase : Any=768 , UpperCAmelCase : List[str]=3072 , UpperCAmelCase : str=512 , UpperCAmelCase : Optional[Any]=12 , UpperCAmelCase : str=12 , UpperCAmelCase : str=3 , UpperCAmelCase : Dict=224 , UpperCAmelCase : Optional[int]=32 , UpperCAmelCase : Optional[Any]="quick_gelu" , UpperCAmelCase : int=1E-5 , UpperCAmelCase : Union[str, Any]=0.0 , UpperCAmelCase : Union[str, Any]=0.0_2 , UpperCAmelCase : int=1.0 , **UpperCAmelCase : List[Any] , ): super().__init__(**A_ ) __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = projection_dim __lowerCamelCase : str = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : int = num_channels __lowerCamelCase : Optional[Any] = patch_size __lowerCamelCase : Tuple = image_size __lowerCamelCase : Union[str, Any] = initializer_range __lowerCamelCase : str = initializer_factor __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : Dict = layer_norm_eps __lowerCamelCase : List[Any] = hidden_act @classmethod def lowerCamelCase__ ( cls : Optional[Any] , UpperCAmelCase : Union[str, os.PathLike] , **UpperCAmelCase : str ): cls._set_token_in_kwargs(A_ ) __lowerCamelCase , __lowerCamelCase : int = cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get("model_type" ) == "altclip": __lowerCamelCase : Dict = 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(A_ , **A_ ) class _snake_case ( _lowercase ): snake_case__ = '''altclip''' snake_case__ = True def __init__( self : Optional[Any] , UpperCAmelCase : str=None , UpperCAmelCase : Tuple=None , UpperCAmelCase : str=768 , UpperCAmelCase : Any=2.6_5_9_2 , **UpperCAmelCase : int ): # 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 : str = kwargs.pop("text_config_dict" , A_ ) __lowerCamelCase : Any = kwargs.pop("vision_config_dict" , A_ ) super().__init__(**A_ ) # 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 : Any = {} # This is the complete result when using `text_config_dict`. __lowerCamelCase : List[Any] = AltCLIPTextConfig(**A_ ).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 : Optional[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(A_ ) # 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 : Any = {} # This is the complete result when using `vision_config_dict`. __lowerCamelCase : List[Any] = AltCLIPVisionConfig(**A_ ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: __lowerCamelCase : Union[str, Any] = { str(A_ ): 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 : List[Any] = ( 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 : Optional[int] = ( F"""`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. """ F"""The value `vision_config[\"{key}\"]` will be overriden.""" ) logger.warning(A_ ) # 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 : Optional[Any] = {} 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(**A_ ) __lowerCamelCase : int = AltCLIPVisionConfig(**A_ ) __lowerCamelCase : str = projection_dim __lowerCamelCase : Union[str, Any] = logit_scale_init_value __lowerCamelCase : Optional[int] = 1.0 @classmethod def lowerCamelCase__ ( cls : Tuple , UpperCAmelCase : AltCLIPTextConfig , UpperCAmelCase : AltCLIPVisionConfig , **UpperCAmelCase : List[Any] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A_ ) def lowerCamelCase__ ( self : int ): __lowerCamelCase : Optional[Any] = copy.deepcopy(self.__dict__ ) __lowerCamelCase : int = self.text_config.to_dict() __lowerCamelCase : Dict = self.vision_config.to_dict() __lowerCamelCase : Dict = self.__class__.model_type return output
646
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : Any ,A_ : int=13 ,A_ : str=7 ,A_ : Tuple=True ,A_ : str=True ,A_ : str=False ,A_ : List[str]=True ,A_ : str=99 ,A_ : str=32 ,A_ : Optional[int]=5 ,A_ : Optional[Any]=4 ,A_ : str=37 ,A_ : Optional[Any]="gelu" ,A_ : Union[str, Any]=0.1 ,A_ : Any=0.1 ,A_ : Optional[Any]=512 ,A_ : str=16 ,A_ : int=2 ,A_ : Optional[Any]=0.02 ,A_ : str=3 ,A_ : str=4 ,A_ : List[str]=None ,) -> str: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = scope def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: return LlamaConfig( 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : Optional[int] ,A_ : Any ,A_ : Optional[Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ) -> List[Any]: A = LlamaModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : int ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Dict ,) -> List[str]: A = True A = LlamaModel(A_ ) model.to(A_ ) model.eval() A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,) A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict ,A_ : Dict ,A_ : Tuple ,A_ : Tuple ,A_ : Dict ,) -> Union[str, Any]: A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Dict ,A_ : Any ,A_ : int ,A_ : List[str] ,A_ : Tuple ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : int ,) -> List[Any]: A = True A = True A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() # first forward pass A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,use_cache=A_ ,) A = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A = ids_tensor((self.batch_size, 3) ,config.vocab_size ) A = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and A = torch.cat([input_ids, next_tokens] ,dim=-1 ) A = torch.cat([input_mask, next_mask] ,dim=-1 ) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,past_key_values=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] # select random slice A = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A = output_from_no_past[:, -3:, random_slice_idx].detach() A = 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 _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _lowerCamelCase: List[Any] = (LlamaForCausalLM,) if is_torch_available() else () _lowerCamelCase: Any = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) _lowerCamelCase: int = False _lowerCamelCase: List[str] = False def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = LlamaModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A = type self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'single_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'multi_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ) -> str: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = ids_tensor([1, 10] ,config.vocab_size ) A = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = LlamaModel(A_ ) original_model.to(A_ ) original_model.eval() A = original_model(A_ ).last_hidden_state A = original_model(A_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = {'type': scaling_type, 'factor': 10.0} A = LlamaModel(A_ ) scaled_model.to(A_ ) scaled_model.eval() A = scaled_model(A_ ).last_hidden_state A = scaled_model(A_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' ,device_map='auto' ) A = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 A = torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) A = torch.tensor( [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # fmt: off A = torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' A = 'Simply put, the theory of relativity states that ' A = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) A = tokenizer.encode(A_ ,return_tensors='pt' ) A = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' ,device_map='sequential' ,use_safetensors=A_ ) # greedy generation outputs A = model.generate(A_ ,max_new_tokens=64 ,top_p=A_ ,temperature=1 ,do_sample=A_ ) A = tokenizer.decode(generated_ids[0] ,skip_special_tokens=A_ ) self.assertEqual(A_ ,A_ )
91
0
'''simple docstring''' from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
539
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers _lowercase = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def _snake_case ( ): A = os.path.dirname(os.path.realpath(snake_case__ ) ) A = os.path.join(snake_case__ , 'words.txt' ) A = '' with open(snake_case__ ) as f: A = f.readline() A = [word.strip('"' ) for word in words.strip('\r\n' ).split(',' )] A = [ word for word in [sum(ord(snake_case__ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(snake_case__ ) if __name__ == "__main__": print(solution())
91
0
A_ : str = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} A_ : Union[str, Any] = ['a', 'b', 'c', 'd', 'e'] def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> str: UpperCamelCase_: str = start # add current to visited visited.append(snake_case__ ) UpperCamelCase_: Optional[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: UpperCamelCase_: Union[str, Any] = topological_sort(snake_case__ , snake_case__ , snake_case__ ) # if all neighbors visited add current to sort sort.append(snake_case__ ) # if all vertices haven't been visited select a new one to visit if len(snake_case__ ) != len(snake_case__ ): for vertice in vertices: if vertice not in visited: UpperCamelCase_: Any = topological_sort(snake_case__ , snake_case__ , snake_case__ ) # return sort return sort if __name__ == "__main__": A_ : Any = topological_sort('a', [], []) print(sort)
57
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''', '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''mobilenet_v1''' def __init__( self : Optional[int] ,A_ : Optional[int]=3 ,A_ : Any=224 ,A_ : List[Any]=1.0 ,A_ : Union[str, Any]=8 ,A_ : Union[str, Any]="relu6" ,A_ : Optional[Any]=True ,A_ : List[str]=0.9_99 ,A_ : int=0.02 ,A_ : int=0.0_01 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) A = num_channels A = image_size A = depth_multiplier A = min_depth A = hidden_act A = tf_padding A = classifier_dropout_prob A = initializer_range A = layer_norm_eps class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> float: return 1e-4
91
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class UpperCamelCase__ : def __init__(self : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : List[Any]=1_3 , snake_case_ : Optional[Any]=7 , snake_case_ : str=True , snake_case_ : List[Any]=True , snake_case_ : List[str]=True , snake_case_ : List[Any]=True , snake_case_ : Optional[int]=9_9 , snake_case_ : int=3_2 , snake_case_ : int=2 , snake_case_ : Any=4 , snake_case_ : Any=3_7 , snake_case_ : str="gelu" , snake_case_ : Tuple=0.1 , snake_case_ : List[str]=0.1 , snake_case_ : Union[str, Any]=5_1_2 , snake_case_ : Optional[int]=1_6 , snake_case_ : Tuple=2 , snake_case_ : Optional[Any]=0.02 , snake_case_ : int=3 , snake_case_ : Tuple=4 , snake_case_ : int=None , snake_case_ : Optional[int]=0 , ): __a : Union[str, Any] = parent __a : Optional[int] = batch_size __a : Optional[int] = seq_length __a : Tuple = is_training __a : Dict = use_input_mask __a : List[str] = use_token_type_ids __a : List[str] = use_labels __a : Dict = vocab_size __a : Optional[int] = hidden_size __a : List[str] = num_hidden_layers __a : List[Any] = num_attention_heads __a : Optional[int] = intermediate_size __a : str = hidden_act __a : List[str] = hidden_dropout_prob __a : Optional[Any] = attention_probs_dropout_prob __a : Dict = max_position_embeddings __a : Optional[Any] = type_vocab_size __a : List[str] = type_sequence_label_size __a : Any = initializer_range __a : Optional[int] = num_labels __a : int = num_choices __a : List[Any] = scope __a : str = projection_dim def lowerCAmelCase (self : List[Any] ): __a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : Optional[int] = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py __a : int = random_attention_mask([self.batch_size, self.seq_length] ) __a : str = None if self.use_token_type_ids: __a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Tuple = None __a : Any = None __a : List[Any] = None if self.use_labels: __a : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : Any = ids_tensor([self.batch_size] , self.num_choices ) __a : List[str] = BertConfig( 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 , ) __a : List[Any] = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase (self : Any , snake_case_ : str , snake_case_ : Tuple , snake_case_ : Optional[int] , snake_case_ : List[str] , snake_case_ : Optional[int] , snake_case_ : Tuple , snake_case_ : List[str] ): __a : Any = TFDPRContextEncoder(config=A_ ) __a : Union[str, Any] = model(A_ , attention_mask=A_ , token_type_ids=A_ ) __a : Any = model(A_ , token_type_ids=A_ ) __a : Dict = model(A_ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def lowerCAmelCase (self : Union[str, Any] , snake_case_ : List[Any] , snake_case_ : Optional[Any] , snake_case_ : Tuple , snake_case_ : Union[str, Any] , snake_case_ : Union[str, Any] , snake_case_ : Optional[Any] , snake_case_ : Tuple ): __a : str = TFDPRQuestionEncoder(config=A_ ) __a : Dict = model(A_ , attention_mask=A_ , token_type_ids=A_ ) __a : Union[str, Any] = model(A_ , token_type_ids=A_ ) __a : Tuple = model(A_ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def lowerCAmelCase (self : Any , snake_case_ : Optional[Any] , snake_case_ : str , snake_case_ : str , snake_case_ : Optional[int] , snake_case_ : str , snake_case_ : str , snake_case_ : List[Any] ): __a : Optional[int] = TFDPRReader(config=A_ ) __a : Any = model(A_ , attention_mask=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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def lowerCAmelCase (self : Dict ): __a : Any = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : str = config_and_inputs __a : int = {'''input_ids''': input_ids} return config, inputs_dict @require_tf class UpperCamelCase__ ( _lowercase ,_lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Any = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE : Any = {'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : str = False _SCREAMING_SNAKE_CASE : int = False _SCREAMING_SNAKE_CASE : List[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False def lowerCAmelCase (self : Dict ): __a : str = TFDPRModelTester(self ) __a : int = ConfigTester(self , config_class=A_ , hidden_size=3_7 ) def lowerCAmelCase (self : int ): self.config_tester.run_common_tests() def lowerCAmelCase (self : List[Any] ): __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*A_ ) def lowerCAmelCase (self : Dict ): __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*A_ ) def lowerCAmelCase (self : Optional[Any] ): __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*A_ ) @slow def lowerCAmelCase (self : Dict ): for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[Any] = TFDPRContextEncoder.from_pretrained(A_ ) self.assertIsNotNone(A_ ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = TFDPRContextEncoder.from_pretrained(A_ ) self.assertIsNotNone(A_ ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = TFDPRQuestionEncoder.from_pretrained(A_ ) self.assertIsNotNone(A_ ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = TFDPRReader.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_tf class UpperCamelCase__ ( unittest.TestCase ): @slow def lowerCAmelCase (self : Optional[Any] ): __a : Optional[int] = TFDPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base''' ) __a : Union[str, Any] = tf.constant( [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]] ) # [CLS] hello, is my dog cute? [SEP] __a : Optional[Any] = model(A_ )[0] # embedding shape = (1, 768) # compare the actual values for a slice. __a : List[str] = tf.constant( [ [ 0.0323_6253, 0.1275_3335, 0.1681_8509, 0.0027_9786, 0.389_6933, 0.2426_4945, 0.217_8971, -0.0233_5227, -0.0848_1959, -0.1432_4117, ] ] ) self.assertTrue(numpy.allclose(output[:, :1_0].numpy() , expected_slice.numpy() , atol=1E-4 ) )
521
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ElectraForCausalLM''', '''ElectraForMaskedLM''', '''ElectraForMultipleChoice''', '''ElectraForPreTraining''', '''ElectraForQuestionAnswering''', '''ElectraForSequenceClassification''', '''ElectraForTokenClassification''', '''ElectraModel''', '''ElectraPreTrainedModel''', '''load_tf_weights_in_electra''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFElectraForMaskedLM''', '''TFElectraForMultipleChoice''', '''TFElectraForPreTraining''', '''TFElectraForQuestionAnswering''', '''TFElectraForSequenceClassification''', '''TFElectraForTokenClassification''', '''TFElectraModel''', '''TFElectraPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxElectraForCausalLM''', '''FlaxElectraForMaskedLM''', '''FlaxElectraForMultipleChoice''', '''FlaxElectraForPreTraining''', '''FlaxElectraForQuestionAnswering''', '''FlaxElectraForSequenceClassification''', '''FlaxElectraForTokenClassification''', '''FlaxElectraModel''', '''FlaxElectraPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
def _a ( a :list[list[int | float]] ) -> List[Any]: a = len(snake_case__ ) a = len(matrix[0] ) a = min(snake_case__ , snake_case__ ) for row in range(snake_case__ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , snake_case__ ): a = matrix[col][row] / matrix[row][row] for i in range(snake_case__ , snake_case__ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows a = True for i in range(row + 1 , snake_case__ ): if matrix[i][row] != 0: a , a = matrix[i], matrix[row] a = False break if reduce: rank -= 1 for i in range(snake_case__ ): a = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
117
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal _lowercase = datasets.utils.logging.get_logger(__name__) _lowercase = ['''names''', '''prefix'''] _lowercase = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] _lowercase = ['''encoding_errors''', '''on_bad_lines'''] _lowercase = ['''date_format'''] @dataclass class lowerCAmelCase_ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCamelCase: str = "," _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[int, List[int], str]] = "infer" _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[Union[int, str, List[int], List[str]]] = None _lowerCamelCase: Optional[Union[List[int], List[str]]] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: Optional[Literal["c", "python", "pyarrow"]] = None _lowerCamelCase: Dict[Union[int, str], Callable[[Any], Any]] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: bool = False _lowerCamelCase: Optional[Union[int, List[int]]] = None _lowerCamelCase: Optional[int] = None _lowerCamelCase: Optional[Union[str, List[str]]] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: bool = True _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = "." _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = '"' _lowerCamelCase: int = 0 _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: int = 0 _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: Optional[str] = None _lowerCamelCase: int = 10000 _lowerCamelCase: Optional[datasets.Features] = None _lowerCamelCase: Optional[str] = "strict" _lowerCamelCase: Literal["error", "warn", "skip"] = "error" _lowerCamelCase: Optional[str] = None def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: if self.delimiter is not None: A = self.delimiter if self.column_names is not None: A = self.column_names @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() ,A_ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class lowerCAmelCase_ ( datasets.ArrowBasedBuilder ): '''simple docstring''' _lowerCamelCase: Any = CsvConfig def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return datasets.DatasetInfo(features=self.config.features ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Any ) -> str: if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A_ ,(str, list, tuple) ): A = data_files if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,gen_kwargs={'files': files} )] A = [] for split_name, files in data_files.items(): if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] splits.append(datasets.SplitGenerator(name=A_ ,gen_kwargs={'files': files} ) ) return splits def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : pa.Table ) -> pa.Table: if self.config.features is not None: A = self.config.features.arrow_schema if all(not require_storage_cast(A_ ) for feature in self.config.features.values() ): # cheaper cast A = pa.Table.from_arrays([pa_table[field.name] for field in schema] ,schema=A_ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A = table_cast(A_ ,A_ ) return pa_table def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ) -> List[Any]: A = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(A_ ) else object for name, dtype, feature in zip(schema.names ,schema.types ,self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(A_ ) ): A = pd.read_csv(A_ ,iterator=A_ ,dtype=A_ ,**self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(A_ ): A = pa.Table.from_pandas(A_ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A_ ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(A_ )}: {e}' ) raise
91
0
"""simple docstring""" def lowerCamelCase_ (UpperCamelCase__ : int ): if divisor % 5 == 0 or divisor % 2 == 0: return 0 _UpperCAmelCase : Tuple = 1 _UpperCAmelCase : int = 1 while repunit: _UpperCAmelCase : Tuple = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def lowerCamelCase_ (UpperCamelCase__ : int = 100_0000 ): _UpperCAmelCase : Dict = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(snake_case__ ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f"{solution() = }")
506
"""simple docstring""" from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Any ,A_ : Callable ,A_ : Optional[Features] = None ,A_ : str = None ,A_ : bool = False ,A_ : bool = False ,A_ : Optional[dict] = None ,A_ : Optional[int] = None ,**A_ : int ,) -> str: super().__init__( features=A_ ,cache_dir=A_ ,keep_in_memory=A_ ,streaming=A_ ,num_proc=A_ ,**A_ ,) A = Generator( cache_dir=A_ ,features=A_ ,generator=A_ ,gen_kwargs=A_ ,**A_ ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: # Build iterable dataset if self.streaming: A = self.builder.as_streaming_dataset(split='train' ) # Build regular (map-style) dataset else: A = None A = None A = None A = None self.builder.download_and_prepare( download_config=A_ ,download_mode=A_ ,verification_mode=A_ ,base_path=A_ ,num_proc=self.num_proc ,) A = self.builder.as_dataset( split='train' ,verification_mode=A_ ,in_memory=self.keep_in_memory ) return dataset
91
0
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class a_ ( unittest.TestCase ): def UpperCamelCase_ ( self ): _lowercase = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] _lowercase = """fp16""" self.assertTrue(is_safetensors_compatible(A_ , variant=A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] _lowercase = """fp16""" self.assertTrue(is_safetensors_compatible(A_ , variant=A_ ) ) def UpperCamelCase_ ( self ): # pass variant but use the non-variant filenames _lowercase = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] _lowercase = """fp16""" self.assertTrue(is_safetensors_compatible(A_ , variant=A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] _lowercase = """fp16""" self.assertFalse(is_safetensors_compatible(A_ , variant=A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] _lowercase = """fp16""" self.assertTrue(is_safetensors_compatible(A_ , variant=A_ ) ) def UpperCamelCase_ ( self ): # pass variant but use the non-variant filenames _lowercase = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] _lowercase = """fp16""" self.assertTrue(is_safetensors_compatible(A_ , variant=A_ ) ) def UpperCamelCase_ ( self ): _lowercase = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] _lowercase = """fp16""" self.assertFalse(is_safetensors_compatible(A_ , variant=A_ ) )
287
"""simple docstring""" from maths.prime_check import is_prime def _snake_case ( snake_case__ : int ): if not isinstance(snake_case__ , snake_case__ ): A = F'Input value of [number={number}] must be an integer' raise TypeError(snake_case__ ) if is_prime(snake_case__ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
91
0
'''simple docstring''' from __future__ import annotations def _snake_case ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int | None = None , _SCREAMING_SNAKE_CASE : int | None = None ) -> str: """simple docstring""" if start is None: lowerCAmelCase = 0 if end is None: lowerCAmelCase = len(snake_case__ ) - 1 if start >= end: return lowerCAmelCase = (start + end) // 2 slowsort(snake_case__ , snake_case__ , snake_case__ ) slowsort(snake_case__ , mid + 1 , snake_case__ ) if sequence[end] < sequence[mid]: lowerCAmelCase, lowerCAmelCase = sequence[mid], sequence[end] slowsort(snake_case__ , snake_case__ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
433
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[str]=0 ) -> str: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = OnnxStableDiffusionImgaImgPipeline.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_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) 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_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.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 ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
91
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf lowerCAmelCase__ = logging.get_logger(__name__) @dataclass class lowerCAmelCase__ ( _lowercase): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self , **__lowerCamelCase) -> str: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: _A : List[Any] = deprecated_arg[3:] _A : Tuple = not kwargs.pop(A_) logger.warning( F"{deprecated_arg} is depreciated. Please use --no-{positive_arg} or" F" {positive_arg}={kwargs[positive_arg]}") _A : Optional[Any] = kwargs.pop("tpu_name" , self.tpu_name) _A : List[str] = kwargs.pop("device_idx" , self.device_idx) _A : int = kwargs.pop("eager_mode" , self.eager_mode) _A : Any = kwargs.pop("use_xla" , self.use_xla) super().__init__(**A_) __SCREAMING_SNAKE_CASE = field( default=_lowercase , metadata={"help": "Name of TPU"} , ) __SCREAMING_SNAKE_CASE = field( default=0 , metadata={"help": "CPU / GPU device index. Defaults to 0."} , ) __SCREAMING_SNAKE_CASE = field(default=_lowercase , metadata={"help": "Benchmark models in eager model."}) __SCREAMING_SNAKE_CASE = field( default=_lowercase , metadata={ "help": "Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`." } , ) @cached_property def _lowerCamelCase ( self) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["tf"]) _A : Optional[Any] = None if self.tpu: try: if self.tpu_name: _A : Optional[int] = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name) else: _A : List[str] = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: _A : Optional[int] = None return tpu @cached_property def _lowerCamelCase ( self) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["tf"]) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu) _A : str = tf.distribute.TPUStrategy(self._setup_tpu) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU") _A : Union[str, Any] = tf.distribute.OneDeviceStrategy(device=F"/gpu:{self.device_idx}") else: tf.config.set_visible_devices([] , "GPU") # disable GPU _A : Union[str, Any] = tf.distribute.OneDeviceStrategy(device=F"/cpu:{self.device_idx}") return strategy @property def _lowerCamelCase ( self) -> bool: requires_backends(self , ["tf"]) return self._setup_tpu is not None @property def _lowerCamelCase ( self) -> "tf.distribute.Strategy": requires_backends(self , ["tf"]) return self._setup_strategy @property def _lowerCamelCase ( self) -> Dict: requires_backends(self , ["tf"]) return tf.config.list_physical_devices("GPU") @property def _lowerCamelCase ( self) -> int: requires_backends(self , ["tf"]) if self.cuda: return len(self.gpu_list) return 0 @property def _lowerCamelCase ( self) -> bool: return self.n_gpu > 0
503
"""simple docstring""" from __future__ import annotations def _snake_case ( snake_case__ : tuple[int, int] , snake_case__ : int ): A , A = position A = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] A = [] for position in positions: A , A = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(snake_case__ ) return permissible_positions def _snake_case ( snake_case__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _snake_case ( snake_case__ : list[list[int]] , snake_case__ : tuple[int, int] , snake_case__ : int ): if is_complete(snake_case__ ): return True for position in get_valid_pos(snake_case__ , len(snake_case__ ) ): A , A = position if board[y][x] == 0: A = curr + 1 if open_knight_tour_helper(snake_case__ , snake_case__ , curr + 1 ): return True A = 0 return False def _snake_case ( snake_case__ : int ): A = [[0 for i in range(snake_case__ )] for j in range(snake_case__ )] for i in range(snake_case__ ): for j in range(snake_case__ ): A = 1 if open_knight_tour_helper(snake_case__ , (i, j) , 1 ): return board A = 0 A = F'Open Kight Tour cannot be performed on a board of size {n}' raise ValueError(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod()
91
0
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 lowercase_ = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "torch_dtype": "float16", "use_bfloat16": True, "tf_legacy_loss": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 1_2_8, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 5_0, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 1_0, "top_p": 0.7, "typical_p": 0.2, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 1_0, "exponential_decay_length_penalty": (5, 1.01), "suppress_tokens": [0, 1], "begin_suppress_tokens": 2, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } @is_staging_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def __UpperCAmelCase ( cls ): __a = TOKEN HfFolder.save_token(A_ ) @classmethod def __UpperCAmelCase ( cls ): try: delete_repo(token=cls._token , repo_id='''test-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-config-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-config''' ) except HTTPError: pass def __UpperCAmelCase ( self ): __a = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''test-config''' , use_auth_token=self._token ) __a = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A_ , getattr(A_ , A_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(A_ , repo_id='''test-config''' , push_to_hub=A_ , use_auth_token=self._token ) __a = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A_ , getattr(A_ , A_ ) ) def __UpperCAmelCase ( self ): __a = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''valid_org/test-config-org''' , use_auth_token=self._token ) __a = BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A_ , getattr(A_ , A_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( A_ , repo_id='''valid_org/test-config-org''' , push_to_hub=A_ , use_auth_token=self._token ) __a = BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A_ , getattr(A_ , A_ ) ) def __UpperCAmelCase ( self ): CustomConfig.register_for_auto_class() __a = CustomConfig(attribute=42 ) config.push_to_hub('''test-dynamic-config''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'''AutoConfig''': '''custom_configuration.CustomConfig'''} ) __a = AutoConfig.from_pretrained(f'''{USER}/test-dynamic-config''' , trust_remote_code=A_ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , '''CustomConfig''' ) self.assertEqual(new_config.attribute , 42 ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __a = c.n_embd + 1 # int __a = c.resid_pdrop + 1.0 # float __a = not c.scale_attn_weights # bool __a = c.summary_type + '''foo''' # str c.update_from_string( f'''n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}''' ) self.assertEqual(A_ , c.n_embd , '''mismatch for key: n_embd''' ) self.assertEqual(A_ , c.resid_pdrop , '''mismatch for key: resid_pdrop''' ) self.assertEqual(A_ , c.scale_attn_weights , '''mismatch for key: scale_attn_weights''' ) self.assertEqual(A_ , c.summary_type , '''mismatch for key: summary_type''' ) def __UpperCAmelCase ( self ): __a = PretrainedConfig() __a = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( A_ , ['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version'''] ) __a = [key for key, value in config_common_kwargs.items() if value == getattr(A_ , A_ )] if len(A_ ) > 0: raise ValueError( '''The following keys are set with the default values in''' ''' `test_configuration_common.config_common_kwargs` pick another value for them:''' f''' {', '.join(A_ )}.''' ) def __UpperCAmelCase ( self ): with self.assertRaises(A_ ): # config is in subfolder, the following should not work without specifying the subfolder __a = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' ) __a = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' , subfolder='''bert''' ) self.assertIsNotNone(A_ ) def __UpperCAmelCase ( self ): # A mock response for an HTTP head request to emulate server down __a = mock.Mock() __a = 500 __a = {} __a = HTTPError __a = {} # Download this model to make sure it's in the cache. __a = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=A_ ) as mock_head: __a = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() def __UpperCAmelCase ( self ): # This test is for deprecated behavior and can be removed in v5 __a = BertConfig.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json''' ) def __UpperCAmelCase ( self ): __a = AutoConfig.from_pretrained('''bert-base-cased''' ) __a = ['''config.4.0.0.json'''] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(A_ ) __a = 2 json.dump(configuration.to_dict() , open(os.path.join(A_ , '''config.4.0.0.json''' ) , '''w''' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __a = AutoConfig.from_pretrained(A_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __a = ['''config.42.0.0.json'''] __a = 768 configuration.save_pretrained(A_ ) shutil.move(os.path.join(A_ , '''config.4.0.0.json''' ) , os.path.join(A_ , '''config.42.0.0.json''' ) ) __a = AutoConfig.from_pretrained(A_ ) self.assertEqual(new_configuration.hidden_size , 768 ) def __UpperCAmelCase ( self ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __a = '''hf-internal-testing/test-two-configs''' import transformers as new_transformers __a = '''v4.0.0''' __a , __a = new_transformers.models.auto.AutoConfig.from_pretrained( A_ , return_unused_kwargs=A_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(A_ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __a = '''v3.0.0''' __a = old_transformers.models.auto.AutoConfig.from_pretrained(A_ ) self.assertEqual(old_configuration.hidden_size , 768 )
695
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Optional[int] = BlenderbotSmallTokenizer _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: super().setUp() A = ['__start__', 'adapt', 'act', 'ap@@', 'te', '__end__', '__unk__'] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['#version: 0.2', 'a p', 't e</w>', 'ap t</w>', 'a d', 'ad apt</w>', 'a c', 'ac t</w>', ''] A = {'unk_token': '__unk__', 'bos_token': '__start__', 'eos_token': '__end__'} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,**A_ : Union[str, Any] ) -> Optional[int]: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Tuple ) -> List[Any]: A = 'adapt act apte' A = 'adapt act apte' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: A = BlenderbotSmallTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) A = 'adapt act apte' A = ['adapt', 'act', 'ap@@', 'te'] A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] A = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) assert tok('sam' ).input_ids == [1384] A = 'I am a small frog.' A = tok([src_text] ,padding=A_ ,truncation=A_ )['input_ids'] A = tok.batch_decode(A_ ,skip_special_tokens=A_ ,clean_up_tokenization_spaces=A_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) A = 'I am a small frog .' A = '.' A = tok(A_ )['input_ids'] A = tok(A_ )['input_ids'] assert encoded[-1] == encoded_dot[0]
91
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCamelCase = { "configuration_convnext": ["CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvNextConfig", "ConvNextOnnxConfig"] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ["ConvNextFeatureExtractor"] UpperCamelCase = ["ConvNextImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ "CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ "TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''image_processor''', '''tokenizer'''] _lowerCamelCase: Optional[int] = '''Pix2StructImageProcessor''' _lowerCamelCase: Dict = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : Optional[int] ,A_ : List[str] ,A_ : Optional[int] ) -> int: A = False super().__init__(A_ ,A_ ) def __call__( self : Any ,A_ : List[str]=None ,A_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,A_ : bool = True ,A_ : Union[bool, str, PaddingStrategy] = False ,A_ : Union[bool, str, TruncationStrategy] = None ,A_ : Optional[int] = None ,A_ : Optional[int] = 2048 ,A_ : int = 0 ,A_ : Optional[int] = None ,A_ : Optional[bool] = None ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = True ,A_ : Optional[Union[str, TensorType]] = None ,**A_ : Tuple ,) -> BatchEncoding: if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None and not self.image_processor.is_vqa: A = self.tokenizer A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,**A_ ) else: # add pixel_values and bbox A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,header_text=A_ ,**A_ ) if text is not None and not self.image_processor.is_vqa: A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) if "attention_mask" in text_encoding: A = text_encoding.pop('attention_mask' ) if "input_ids" in text_encoding: A = text_encoding.pop('input_ids' ) else: A = None if text_encoding is not None: encoding_image_processor.update(A_ ) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,*A_ : Optional[Any] ,**A_ : Dict ) -> Union[str, Any]: return self.tokenizer.batch_decode(*A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,*A_ : Tuple ,**A_ : List[str] ) -> Any: return self.tokenizer.decode(*A_ ,**A_ ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: A = self.tokenizer.model_input_names A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
91
0
"""simple docstring""" import math from collections.abc import Callable def lowercase_ ( _lowerCamelCase: Callable[[float], float] , _lowerCamelCase: float , _lowerCamelCase: float ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase : Union[str, Any] = xa __lowerCamelCase : Optional[int] = xa while True: if x_n == x_na or function(snake_case__ ) == function(snake_case__ ): raise ZeroDivisionError("float division by zero, could not find root" ) __lowerCamelCase : Union[str, Any] = x_na - ( function(snake_case__ ) / ((function(snake_case__ ) - function(snake_case__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na __lowerCamelCase : str = x_na __lowerCamelCase : List[Any] = x_na def lowercase_ ( _lowerCamelCase: float ) -> Union[str, Any]: '''simple docstring''' return math.pow(snake_case__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
646
"""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 _lowercase = logging.get_logger(__name__) _lowercase = '''▁''' _lowercase = {'''vocab_file''': '''sentencepiece.bpe.model'''} _lowercase = { '''vocab_file''': { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model''' ), } } _lowercase = { '''xlm-roberta-base''': 5_12, '''xlm-roberta-large''': 5_12, '''xlm-roberta-large-finetuned-conll02-dutch''': 5_12, '''xlm-roberta-large-finetuned-conll02-spanish''': 5_12, '''xlm-roberta-large-finetuned-conll03-english''': 5_12, '''xlm-roberta-large-finetuned-conll03-german''': 5_12, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[str] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] ,A_ : str ,A_ : str="<s>" ,A_ : Any="</s>" ,A_ : Tuple="</s>" ,A_ : Any="<s>" ,A_ : Optional[Any]="<unk>" ,A_ : int="<pad>" ,A_ : str="<mask>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : Optional[int] ,) -> None: # Mask token behave like a normal word, i.e. include the space before it A = AddedToken(A_ ,lstrip=A_ ,rstrip=A_ ) if isinstance(A_ ,A_ ) else mask_token A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,sep_token=A_ ,cls_token=A_ ,pad_token=A_ ,mask_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) A = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token A = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab A = 1 A = len(self.sp_model ) + self.fairseq_offset A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ) -> Any: A = self.__dict__.copy() A = None A = self.sp_model.serialized_model_proto() return state def __setstate__( self : str ,A_ : str ) -> Optional[Any]: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A = [self.cls_token_id] A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: A = [self.sep_token_id] A = [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 _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[Any] ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] A = self.sp_model.PieceToId(A_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> int: 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 _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = ''.join(A_ ).replace(A_ ,' ' ).strip() return out_string def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
91
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ = { "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"], "tokenization_lxmert": ["LxmertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = ["LxmertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "LxmertEncoder", "LxmertForPreTraining", "LxmertForQuestionAnswering", "LxmertModel", "LxmertPreTrainedModel", "LxmertVisualFeatureEncoder", "LxmertXLayer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLxmertForPreTraining", "TFLxmertMainLayer", "TFLxmertModel", "TFLxmertPreTrainedModel", "TFLxmertVisualFeatureEncoder", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
539
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Tuple = logging.get_logger(__name__) A_ : Optional[int] = { 'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json', 'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json', 'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json', } class _lowerCAmelCase( _lowercase ): """simple docstring""" a : Any ='''owlvit_text_model''' def __init__( self , _lowerCamelCase=4_9_4_0_8 , _lowerCamelCase=5_1_2 , _lowerCamelCase=2_0_4_8 , _lowerCamelCase=1_2 , _lowerCamelCase=8 , _lowerCamelCase=1_6 , _lowerCamelCase="quick_gelu" , _lowerCamelCase=1e-5 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1.0 , _lowerCamelCase=0 , _lowerCamelCase=4_9_4_0_6 , _lowerCamelCase=4_9_4_0_7 , **_lowerCamelCase , ): super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) UpperCamelCase_: Dict = vocab_size UpperCamelCase_: List[str] = hidden_size UpperCamelCase_: List[Any] = intermediate_size UpperCamelCase_: Union[str, Any] = num_hidden_layers UpperCamelCase_: Union[str, Any] = num_attention_heads UpperCamelCase_: int = max_position_embeddings UpperCamelCase_: List[str] = hidden_act UpperCamelCase_: Dict = layer_norm_eps UpperCamelCase_: Dict = attention_dropout UpperCamelCase_: Optional[int] = initializer_range UpperCamelCase_: str = initializer_factor @classmethod def _a ( cls , _lowerCamelCase , **_lowerCamelCase ): cls._set_token_in_kwargs(A_ ) UpperCamelCase_ ,UpperCamelCase_: Any = cls.get_config_dict(A_ , **A_ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('model_type' ) == "owlvit": UpperCamelCase_: str = config_dict['text_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(A_ , **A_ ) class _lowerCAmelCase( _lowercase ): """simple docstring""" a : List[Any] ='''owlvit_vision_model''' def __init__( self , _lowerCamelCase=7_6_8 , _lowerCamelCase=3_0_7_2 , _lowerCamelCase=1_2 , _lowerCamelCase=1_2 , _lowerCamelCase=3 , _lowerCamelCase=7_6_8 , _lowerCamelCase=3_2 , _lowerCamelCase="quick_gelu" , _lowerCamelCase=1e-5 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1.0 , **_lowerCamelCase , ): super().__init__(**A_ ) UpperCamelCase_: str = hidden_size UpperCamelCase_: Optional[int] = intermediate_size UpperCamelCase_: Optional[Any] = num_hidden_layers UpperCamelCase_: Dict = num_attention_heads UpperCamelCase_: Optional[Any] = num_channels UpperCamelCase_: Optional[Any] = image_size UpperCamelCase_: Any = patch_size UpperCamelCase_: str = hidden_act UpperCamelCase_: List[str] = layer_norm_eps UpperCamelCase_: List[Any] = attention_dropout UpperCamelCase_: Dict = initializer_range UpperCamelCase_: List[str] = initializer_factor @classmethod def _a ( cls , _lowerCamelCase , **_lowerCamelCase ): cls._set_token_in_kwargs(A_ ) UpperCamelCase_ ,UpperCamelCase_: Any = cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('model_type' ) == "owlvit": UpperCamelCase_: 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(A_ , **A_ ) class _lowerCAmelCase( _lowercase ): """simple docstring""" a : Optional[Any] ='''owlvit''' a : List[str] =True def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=5_1_2 , _lowerCamelCase=2.6_5_9_2 , _lowerCamelCase=True , **_lowerCamelCase , ): super().__init__(**A_ ) if text_config is None: UpperCamelCase_: Optional[Any] = {} logger.info('text_config is None. Initializing the OwlViTTextConfig with default values.' ) if vision_config is None: UpperCamelCase_: List[str] = {} logger.info('vision_config is None. initializing the OwlViTVisionConfig with default values.' ) UpperCamelCase_: Optional[Any] = OwlViTTextConfig(**A_ ) UpperCamelCase_: List[Any] = OwlViTVisionConfig(**A_ ) UpperCamelCase_: Union[str, Any] = projection_dim UpperCamelCase_: List[str] = logit_scale_init_value UpperCamelCase_: Any = return_dict UpperCamelCase_: Optional[int] = 1.0 @classmethod def _a ( cls , _lowerCamelCase , **_lowerCamelCase ): cls._set_token_in_kwargs(A_ ) UpperCamelCase_ ,UpperCamelCase_: Optional[Any] = cls.get_config_dict(A_ , **A_ ) 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(A_ , **A_ ) @classmethod def _a ( cls , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ): UpperCamelCase_: Any = {} UpperCamelCase_: Tuple = text_config UpperCamelCase_: Dict = vision_config return cls.from_dict(A_ , **A_ ) def _a ( self ): UpperCamelCase_: Dict = copy.deepcopy(self.__dict__ ) UpperCamelCase_: Optional[int] = self.text_config.to_dict() UpperCamelCase_: List[Any] = self.vision_config.to_dict() UpperCamelCase_: Union[str, Any] = self.__class__.model_type return output class _lowerCAmelCase( _lowercase ): """simple docstring""" @property def _a ( self ): return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ] ) @property def _a ( self ): return OrderedDict( [ ('logits_per_image', {0: 'batch'}), ('logits_per_text', {0: 'batch'}), ('text_embeds', {0: 'batch'}), ('image_embeds', {0: 'batch'}), ] ) @property def _a ( self ): return 1e-4 def _a ( self , _lowerCamelCase , _lowerCamelCase = -1 , _lowerCamelCase = -1 , _lowerCamelCase = None , ): UpperCamelCase_: Optional[Any] = super().generate_dummy_inputs( processor.tokenizer , batch_size=A_ , seq_length=A_ , framework=A_ ) UpperCamelCase_: Any = super().generate_dummy_inputs( processor.image_processor , batch_size=A_ , framework=A_ ) return {**text_input_dict, **image_input_dict} @property def _a ( self ): return 1_4
57
"""simple docstring""" from torch import nn def _snake_case ( snake_case__ : Union[str, Any] ): 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}' )
91
0
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def __UpperCamelCase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : int ): __a : Optional[Any] = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg''' __a : Optional[int] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ).convert('''RGB''' ) __a : List[Any] = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73) , (0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11) ), ] ) __a : Any = transform(snake_case__ ).unsqueeze(0 ).to(snake_case__ ) return image def __UpperCamelCase ( lowerCAmelCase__ : Optional[Any] ): if "visual_encoder" in key: __a : Optional[Any] = re.sub('''visual_encoder*''' , '''vision_model.encoder''' , snake_case__ ) if "blocks" in key: __a : Optional[int] = re.sub(R'''blocks''' , '''layers''' , snake_case__ ) if "attn" in key: __a : str = re.sub(R'''attn''' , '''self_attn''' , snake_case__ ) if "norm1" in key: __a : Union[str, Any] = re.sub(R'''norm1''' , '''layer_norm1''' , snake_case__ ) if "norm2" in key: __a : List[Any] = re.sub(R'''norm2''' , '''layer_norm2''' , snake_case__ ) if "encoder.norm" in key: __a : List[Any] = re.sub(R'''encoder.norm''' , '''post_layernorm''' , snake_case__ ) if "encoder.patch_embed.proj" in key: __a : List[Any] = re.sub(R'''encoder.patch_embed.proj''' , '''embeddings.patch_embedding''' , snake_case__ ) if "encoder.pos_embed" in key: __a : str = re.sub(R'''encoder.pos_embed''' , '''embeddings.position_embedding''' , snake_case__ ) if "encoder.cls_token" in key: __a : Any = re.sub(R'''encoder.cls_token''' , '''embeddings.class_embedding''' , snake_case__ ) if "self_attn" in key: __a : Optional[int] = re.sub(R'''self_attn.proj''' , '''self_attn.projection''' , snake_case__ ) return key @torch.no_grad() def __UpperCamelCase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : str=None ): if config_path is not None: __a : Union[str, Any] = BlipConfig.from_pretrained(snake_case__ ) else: __a : Optional[Any] = BlipConfig(projection_dim=5_1_2 , text_config={} , vision_config={} ) __a : Optional[Any] = BlipForConditionalGeneration(snake_case__ ).eval() __a : Optional[int] = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth''' __a : Optional[Any] = blip_decoder(pretrained=snake_case__ , image_size=3_8_4 , vit='''base''' ) __a : str = pt_model.eval() __a : Optional[int] = pt_model.state_dict() for key in modified_state_dict.copy(): __a : Tuple = modified_state_dict.pop(snake_case__ ) __a : Dict = rename_key(snake_case__ ) __a : Union[str, Any] = value hf_model.load_state_dict(snake_case__ ) __a : List[str] = 3_8_4 __a : Any = load_demo_image(image_size=snake_case__ , device='''cpu''' ) __a : str = BertTokenizer.from_pretrained('''bert-base-uncased''' ) __a : List[str] = tokenizer(['''a picture of'''] ).input_ids __a : Optional[Any] = hf_model.generate(snake_case__ , snake_case__ ) assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 3_8_6_1, 1_9_9_7, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2] __a : List[str] = hf_model.generate(snake_case__ ) assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case__ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' __a : int = ( '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth''' ) __a : Any = blip_vqa(pretrained=snake_case__ , image_size=snake_case__ , vit='''base''' ) vqa_model.eval() __a : Optional[int] = vqa_model.state_dict() for key in modified_state_dict.copy(): __a : Any = modified_state_dict.pop(snake_case__ ) __a : Any = rename_key(snake_case__ ) __a : Union[str, Any] = value __a : int = BlipForQuestionAnswering(snake_case__ ) hf_vqa_model.load_state_dict(snake_case__ ) __a : int = ['''How many dogs are in this image?'''] __a : Dict = tokenizer(snake_case__ , return_tensors='''pt''' ).input_ids __a : List[Any] = hf_vqa_model.generate(snake_case__ , snake_case__ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' ) __a : int = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth''' __a : Optional[Any] = blip_itm(pretrained=snake_case__ , image_size=snake_case__ , vit='''base''' ) itm_model.eval() __a : str = itm_model.state_dict() for key in modified_state_dict.copy(): __a : Any = modified_state_dict.pop(snake_case__ ) __a : Union[str, Any] = rename_key(snake_case__ ) __a : Any = value __a : Dict = BlipForImageTextRetrieval(snake_case__ ) __a : Dict = ['''A picture of a woman with a dog sitting in a beach'''] __a : Tuple = tokenizer( snake_case__ , return_tensors='''pt''' , padding='''max_length''' , truncation=snake_case__ , max_length=3_5 , ).input_ids hf_itm_model.load_state_dict(snake_case__ ) hf_itm_model.eval() __a : List[str] = hf_itm_model(snake_case__ , snake_case__ , use_itm_head=snake_case__ ) __a : int = hf_itm_model(snake_case__ , snake_case__ , use_itm_head=snake_case__ ) assert out[0].item() == 0.21_10_68_74_94_27_79_54 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_56_98_84_53_86_50_51_27 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' ) if __name__ == "__main__": lowercase__ =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') lowercase__ =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
521
"""simple docstring""" import copy import re class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str = '''hp''' _lowerCamelCase: List[Any] = {} _lowerCamelCase: List[Any] = None @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,A_ : List[str] ,A_ : Optional[Any] ) -> Tuple: A = prefix A = defaults cls.build_naming_info() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Any ,A_ : List[Any] ) -> int: if len(A_ ) == 0: return "" A = None if any(char.isdigit() for char in word ): raise Exception(F'Parameters should not contain numbers: \'{word}\' contains a number' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 ,len(A_ ) + 1 ): A = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: A = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(A_ : Optional[Any] ): A = '' while integer != 0: A = chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s A = 0 while True: A = word + '#' + int_to_alphabetic(A_ ) if sword in info["reverse_short_word"]: continue else: A = sword break A = short_word A = word return short_word @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[Any] ,A_ : Union[str, Any] ) -> Union[str, Any]: A = param_name.split('_' ) A = [TrialShortNamer.shortname_for_word(A_ ,A_ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name A = ['', '_'] for separator in separators: A = separator.join(A_ ) if shortname not in info["reverse_short_param"]: A = shortname A = param_name return shortname return param_name @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[Any] ,A_ : Any ) -> Tuple: A = TrialShortNamer.shortname_for_key(A_ ,A_ ) A = short_name A = param_name @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ) -> List[Any]: if cls.NAMING_INFO is not None: return A = { 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } A = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(A_ ,A_ ) A = info @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,A_ : Union[str, Any] ) -> Union[str, Any]: cls.build_naming_info() assert cls.PREFIX is not None A = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F'You should provide a default value for the param name {k} with value {v}' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue A = cls.NAMING_INFO['short_param'][k] if isinstance(A_ ,A_ ): A = 1 if v else 0 A = '' if isinstance(A_ ,(int, float) ) else '-' A = F'{key}{sep}{v}' name.append(A_ ) return "_".join(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,A_ : Any ) -> int: A = repr[len(cls.PREFIX ) + 1 :] if repr == "": A = [] else: A = repr.split('_' ) A = {} for value in values: if "-" in value: A , A = value.split('-' ) else: A = re.sub('[0-9.]' ,'' ,A_ ) A = float(re.sub('[^0-9.]' ,'' ,A_ ) ) A = cls.NAMING_INFO['reverse_short_param'][p_k] A = p_v for k in cls.DEFAULTS: if k not in parameters: A = cls.DEFAULTS[k] return parameters
91
0
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging UpperCAmelCase__ = logging.get_logger(__name__) def _a ( a :Dict=None , a :Optional[int]=None ) -> Any: return field(default_factory=lambda: default , metadata=snake_case__ ) @dataclass class lowercase_ : '''simple docstring''' __snake_case = list_field( default=[] , metadata={ '''help''': ( '''Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version''' ''' of all available models''' ) } , ) __snake_case = list_field( default=[8] , metadata={'''help''': '''List of batch sizes for which memory and time performance will be evaluated'''} ) __snake_case = list_field( default=[8, 32, 1_28, 5_12] , metadata={'''help''': '''List of sequence lengths for which memory and time performance will be evaluated'''} , ) __snake_case = field( default=_lowercase , metadata={'''help''': '''Whether to benchmark inference of model. Inference can be disabled via --no-inference.'''} , ) __snake_case = field( default=_lowercase , metadata={'''help''': '''Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'''} , ) __snake_case = field( default=_lowercase , metadata={'''help''': '''Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'''} ) __snake_case = field(default=_lowercase , metadata={'''help''': '''Use FP16 to accelerate inference.'''} ) __snake_case = field(default=_lowercase , metadata={'''help''': '''Benchmark training of model'''} ) __snake_case = field(default=_lowercase , metadata={'''help''': '''Verbose memory tracing'''} ) __snake_case = field( default=_lowercase , metadata={'''help''': '''Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'''} , ) __snake_case = field( default=_lowercase , metadata={ '''help''': '''Whether to perform memory measurements. Memory measurements can be disabled via --no-memory''' } , ) __snake_case = field(default=_lowercase , metadata={'''help''': '''Trace memory line by line'''} ) __snake_case = field(default=_lowercase , metadata={'''help''': '''Save result to a CSV file'''} ) __snake_case = field(default=_lowercase , metadata={'''help''': '''Save all print statements in a log file'''} ) __snake_case = field(default=_lowercase , metadata={'''help''': '''Whether to print environment information'''} ) __snake_case = field( default=_lowercase , metadata={ '''help''': ( '''Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use''' ''' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled''' ''' for debugging / testing and on TPU.''' ) } , ) __snake_case = field( default=f'''inference_time_{round(time() )}.csv''' , metadata={'''help''': '''CSV filename used if saving time results to csv.'''} , ) __snake_case = field( default=f'''inference_memory_{round(time() )}.csv''' , metadata={'''help''': '''CSV filename used if saving memory results to csv.'''} , ) __snake_case = field( default=f'''train_time_{round(time() )}.csv''' , metadata={'''help''': '''CSV filename used if saving time results to csv for training.'''} , ) __snake_case = field( default=f'''train_memory_{round(time() )}.csv''' , metadata={'''help''': '''CSV filename used if saving memory results to csv for training.'''} , ) __snake_case = field( default=f'''env_info_{round(time() )}.csv''' , metadata={'''help''': '''CSV filename used if saving environment information.'''} , ) __snake_case = field( default=f'''log_{round(time() )}.csv''' , metadata={'''help''': '''Log filename used if print statements are saved in log.'''} , ) __snake_case = field(default=3 , metadata={'''help''': '''Times an experiment will be run.'''} ) __snake_case = field( default=_lowercase , metadata={ '''help''': ( '''Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain''' ''' model weights.''' ) } , ) def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" warnings.warn( F"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , A_ , ) def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
117
"""simple docstring""" import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def _snake_case ( ): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(snake_case__ ): requests.request('GET' , 'https://huggingface.co' ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request('GET' , 'https://huggingface.co' , timeout=1.0 ) @pytest.mark.integration def _snake_case ( ): with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request('GET' , 'https://huggingface.co' ) def _snake_case ( ): with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(snake_case__ ): http_head('https://huggingface.co' )
91
0
"""simple docstring""" import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase_ (): _UpperCAmelCase : int = '''https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg''' _UpperCAmelCase : Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ).convert('''RGB''' ) return image def lowerCamelCase_ (UpperCamelCase__ : Optional[int] ): _UpperCAmelCase : Any = [] # fmt: off # vision encoder rename_keys.append(('''visual_encoder.cls_token''', '''vision_model.embeddings.class_embedding''') ) rename_keys.append(('''visual_encoder.pos_embed''', '''vision_model.embeddings.position_embedding''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.weight''', '''vision_model.embeddings.patch_embedding.weight''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.bias''', '''vision_model.embeddings.patch_embedding.bias''') ) rename_keys.append(('''ln_vision.weight''', '''vision_model.post_layernorm.weight''') ) rename_keys.append(('''ln_vision.bias''', '''vision_model.post_layernorm.bias''') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'visual_encoder.blocks.{i}.norm1.weight', F'vision_model.encoder.layers.{i}.layer_norm1.weight') ) rename_keys.append((F'visual_encoder.blocks.{i}.norm1.bias', F'vision_model.encoder.layers.{i}.layer_norm1.bias') ) rename_keys.append((F'visual_encoder.blocks.{i}.norm2.weight', F'vision_model.encoder.layers.{i}.layer_norm2.weight') ) rename_keys.append((F'visual_encoder.blocks.{i}.norm2.bias', F'vision_model.encoder.layers.{i}.layer_norm2.bias') ) rename_keys.append((F'visual_encoder.blocks.{i}.attn.qkv.weight', F'vision_model.encoder.layers.{i}.self_attn.qkv.weight') ) rename_keys.append((F'visual_encoder.blocks.{i}.attn.proj.weight', F'vision_model.encoder.layers.{i}.self_attn.projection.weight',) ) rename_keys.append((F'visual_encoder.blocks.{i}.attn.proj.bias', F'vision_model.encoder.layers.{i}.self_attn.projection.bias') ) rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc1.weight', F'vision_model.encoder.layers.{i}.mlp.fc1.weight') ) rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc1.bias', F'vision_model.encoder.layers.{i}.mlp.fc1.bias') ) rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc2.weight', F'vision_model.encoder.layers.{i}.mlp.fc2.weight') ) rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc2.bias', F'vision_model.encoder.layers.{i}.mlp.fc2.bias') ) # QFormer rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.weight''', '''qformer.embeddings.layernorm.weight''') ) rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.embeddings.layernorm.bias''') ) # fmt: on return rename_keys def lowerCamelCase_ (UpperCamelCase__ : Dict , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] ): _UpperCAmelCase : str = dct.pop(snake_case__ ) _UpperCAmelCase : Optional[Any] = val def lowerCamelCase_ (UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] ): for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases _UpperCAmelCase : List[Any] = state_dict.pop(F'visual_encoder.blocks.{i}.attn.q_bias' ) _UpperCAmelCase : int = state_dict.pop(F'visual_encoder.blocks.{i}.attn.v_bias' ) # next, set bias in the state dict _UpperCAmelCase : Optional[Any] = torch.cat((q_bias, torch.zeros_like(snake_case__ , requires_grad=snake_case__ ), v_bias) ) _UpperCAmelCase : Any = qkv_bias def lowerCamelCase_ (UpperCamelCase__ : Tuple ): _UpperCAmelCase : Optional[Any] = 364 if '''coco''' in model_name else 224 _UpperCAmelCase : Any = InstructBlipVisionConfig(image_size=snake_case__ ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: _UpperCAmelCase : List[Any] = TaConfig.from_pretrained('''google/flan-t5-xl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: _UpperCAmelCase : Tuple = TaConfig.from_pretrained('''google/flan-t5-xxl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: _UpperCAmelCase : Dict = LlamaConfig.from_pretrained('''decapoda-research/llama-7b-hf''' , vocab_size=3_2001 ).to_dict() elif "vicuna-13b" in model_name: _UpperCAmelCase : int = LlamaConfig.from_pretrained('''decapoda-research/llama-13b-hf''' , vocab_size=3_2001 ).to_dict() else: raise ValueError('''Model name not supported''' ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 _UpperCAmelCase : Union[str, Any] = InstructBlipQFormerConfig(vocab_size=3_0523 ).to_dict() _UpperCAmelCase : int = InstructBlipConfig(vision_config=snake_case__ , text_config=snake_case__ , qformer_config=snake_case__ ) return config, image_size @torch.no_grad() def lowerCamelCase_ (UpperCamelCase__ : Tuple , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : List[Any]=False ): _UpperCAmelCase : List[Any] = AutoTokenizer.from_pretrained('''bert-base-uncased''' , truncation_side='''left''' ) qformer_tokenizer.add_special_tokens({'''bos_token''': '''[DEC]'''} ) if "t5" in model_name: _UpperCAmelCase : Tuple = TaTokenizerFast.from_pretrained('''google/flan-t5-xl''' , truncation_side='''left''' ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) _UpperCAmelCase : Dict = LlamaTokenizerFast.from_pretrained( '''huggyllama/llama-7b''' , truncation_side='''left''' , bos_token='''</s>''' , unk_token='''</s>''' ) tokenizer.add_special_tokens({'''pad_token''': '''[PAD]'''} ) _UpperCAmelCase , _UpperCAmelCase : int = get_blipa_config(snake_case__ ) _UpperCAmelCase : List[str] = InstructBlipForConditionalGeneration(snake_case__ ).eval() _UpperCAmelCase : List[str] = { '''instructblip-vicuna-7b''': ('''blip2_vicuna_instruct''', '''vicuna7b'''), '''instructblip-vicuna-13b''': ('''blip2_vicuna_instruct''', '''vicuna13b'''), '''instructblip-flan-t5-xl''': ('''blip2_t5_instruct''', '''flant5xl'''), '''instructblip-flan-t5-xxl''': ('''blip2_t5_instruct''', '''flant5xxl'''), } _UpperCAmelCase , _UpperCAmelCase : str = model_name_to_original[model_name] # load original model print('''Loading original model...''' ) _UpperCAmelCase : Any = '''cuda:1''' if torch.cuda.is_available() else '''cpu''' _UpperCAmelCase : int = '''cuda:2''' if torch.cuda.is_available() else '''cpu''' _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Optional[int] = load_model_and_preprocess( name=snake_case__ , model_type=snake_case__ , is_eval=snake_case__ , device=snake_case__ ) original_model.eval() print('''Done!''' ) # update state dict keys _UpperCAmelCase : Optional[int] = original_model.state_dict() _UpperCAmelCase : Optional[int] = create_rename_keys(snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): _UpperCAmelCase : Tuple = state_dict.pop(snake_case__ ) if key.startswith('''Qformer.bert''' ): _UpperCAmelCase : Any = key.replace('''Qformer.bert''' , '''qformer''' ) if "attention.self" in key: _UpperCAmelCase : Dict = key.replace('''self''' , '''attention''' ) if "llm_proj" in key: _UpperCAmelCase : Optional[Any] = key.replace('''llm_proj''' , '''language_projection''' ) if "t5_proj" in key: _UpperCAmelCase : Optional[int] = key.replace('''t5_proj''' , '''language_projection''' ) if key.startswith('''llm_model''' ): _UpperCAmelCase : Tuple = key.replace('''llm_model''' , '''language_model''' ) if key.startswith('''t5''' ): _UpperCAmelCase : int = key.replace('''t5''' , '''language''' ) _UpperCAmelCase : Optional[int] = val # read in qv biases read_in_q_v_bias(snake_case__ , snake_case__ ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(snake_case__ , strict=snake_case__ ) _UpperCAmelCase : Dict = load_demo_image() _UpperCAmelCase : List[Any] = '''What is unusual about this image?''' # create processor _UpperCAmelCase : Optional[Any] = BlipImageProcessor( size={'''height''': image_size, '''width''': image_size} , image_mean=snake_case__ , image_std=snake_case__ ) _UpperCAmelCase : Optional[int] = InstructBlipProcessor( image_processor=snake_case__ , tokenizer=snake_case__ , qformer_tokenizer=snake_case__ , ) _UpperCAmelCase : List[str] = processor(images=snake_case__ , text=snake_case__ , return_tensors='''pt''' ).to(snake_case__ ) # make sure processor creates exact same pixel values _UpperCAmelCase : Optional[Any] = vis_processors['''eval'''](snake_case__ ).unsqueeze(0 ).to(snake_case__ ) _UpperCAmelCase : int = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ) , snake_case__ ) original_model.to(snake_case__ ) hf_model.to(snake_case__ ) with torch.no_grad(): if "vicuna" in model_name: _UpperCAmelCase : List[str] = original_model({'''image''': original_pixel_values, '''text_input''': [prompt]} ).logits _UpperCAmelCase : Union[str, Any] = hf_model(**snake_case__ ).logits else: _UpperCAmelCase : int = original_model( {'''image''': original_pixel_values, '''text_input''': [prompt], '''text_output''': ['''\n''']} ).logits _UpperCAmelCase : Optional[int] = tokenizer('''\n''' , return_tensors='''pt''' ).input_ids.to(snake_case__ ) _UpperCAmelCase : Optional[Any] = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100 ) _UpperCAmelCase : Optional[int] = hf_model(**snake_case__ , labels=snake_case__ ).logits print('''First values of original logits:''' , original_logits[0, :3, :3] ) print('''First values of HF logits:''' , logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape _UpperCAmelCase : List[str] = 1E-4 if '''vicuna''' in model_name else 1E-5 assert torch.allclose(original_logits.to(logits.device ) , snake_case__ , atol=snake_case__ ) print('''Looks ok!''' ) print('''Generating with original model...''' ) _UpperCAmelCase : Optional[int] = original_model.generate({'''image''': original_pixel_values, '''prompt''': prompt} , num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print('''Generating with HF model...''' ) _UpperCAmelCase : Optional[int] = hf_model.generate( **snake_case__ , do_sample=snake_case__ , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? _UpperCAmelCase : Dict = 2 print('''Original generation:''' , snake_case__ ) _UpperCAmelCase : Tuple = processor.batch_decode(snake_case__ , skip_special_tokens=snake_case__ ) _UpperCAmelCase : Optional[int] = [text.strip() for text in output_text] print('''HF generation:''' , snake_case__ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(snake_case__ ) hf_model.save_pretrained(snake_case__ ) if push_to_hub: processor.push_to_hub(F'Salesforce/{model_name}' ) hf_model.push_to_hub(F'Salesforce/{model_name}' ) if __name__ == "__main__": _lowerCAmelCase :List[Any] = argparse.ArgumentParser() _lowerCAmelCase :Optional[Any] = [ 'instructblip-vicuna-7b', 'instructblip-vicuna-13b', 'instructblip-flan-t5-xl', 'instructblip-flan-t5-xxl', ] parser.add_argument( '--model_name', default='instructblip-flan-t5-xl', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) _lowerCAmelCase :Optional[Any] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
506
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[str] = BioGptTokenizer _lowerCamelCase: Tuple = False def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ) as fp: fp.write(json.dumps(A_ ) ) with open(self.merges_file ,'w' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple ) -> int: A = 'lower newer' A = 'lower newer' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = BioGptTokenizer(self.vocab_file ,self.merges_file ) A = 'lower' A = ['low', 'er</w>'] A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = tokens + ['<unk>'] A = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) A = tokenizer.encode('sequence builders' ,add_special_tokens=A_ ) A = tokenizer.encode('multi-sequence build' ,add_special_tokens=A_ ) A = tokenizer.build_inputs_with_special_tokens(A_ ) A = tokenizer.build_inputs_with_special_tokens(A_ ,A_ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
91
0
from __future__ import annotations from typing import Any class a_ ( _lowercase ): pass class a_ : def __init__( self , __UpperCamelCase ): _lowercase = data _lowercase = None def __iter__( self ): _lowercase = self _lowercase = [] while node: if node in visited: raise ContainsLoopError visited.append(A_ ) yield node.data _lowercase = node.next_node @property def UpperCamelCase_ ( self ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": A : Optional[Any] = Node(1) A : Optional[int] = Node(2) A : str = Node(3) A : Any = Node(4) print(root_node.has_loop) # False A : List[str] = root_node.next_node print(root_node.has_loop) # True A : Optional[int] = Node(5) A : Any = Node(6) A : List[Any] = Node(5) A : List[str] = Node(6) print(root_node.has_loop) # False A : List[Any] = Node(1) print(root_node.has_loop) # False
287
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers _lowercase = float('''nan''') class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[str] ,A_ : Tuple ) -> Any: A = sys.stdout A = open(A_ ,'a' ) def __getattr__( self : int ,A_ : Optional[Any] ) -> Tuple: return getattr(self.stdout ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> str: self.stdout.write(A_ ) # strip tqdm codes self.file.write(re.sub(R'^.*\r' ,'' ,A_ ,0 ,re.M ) ) def _snake_case ( snake_case__ : Optional[Any]=80 , snake_case__ : List[str]=False ): A = [] # deal with critical env vars A = ['CUDA_VISIBLE_DEVICES'] for key in env_keys: A = os.environ.get(snake_case__ , snake_case__ ) if val is not None: cmd.append(F'{key}={val}' ) # python executable (not always needed if the script is executable) A = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(snake_case__ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes A = [] A = '' while len(snake_case__ ) > 0: current_line += F'{cmd.pop(0 )} ' if len(snake_case__ ) == 0 or len(snake_case__ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(snake_case__ ) A = '' return "\\\n".join(snake_case__ ) def _snake_case ( snake_case__ : str , snake_case__ : str ): # unwrap multi-line input A = re.sub(r'[\\\n]+' , ' ' , args.base_cmd ) # remove --output_dir if any and set our own A = re.sub('--output_dir\s+[^\s]+' , '' , args.base_cmd ) args.base_cmd += F' --output_dir {output_dir}' # ensure we have --overwrite_output_dir A = re.sub('--overwrite_output_dir\s+' , '' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _snake_case ( snake_case__ : List[str] , snake_case__ : Union[str, Any] , snake_case__ : str , snake_case__ : int , snake_case__ : Optional[Any] , snake_case__ : Any , snake_case__ : List[Any] ): # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , ) A = subprocess.run(snake_case__ , capture_output=snake_case__ , text=snake_case__ ) if verbose: print('STDOUT' , result.stdout ) print('STDERR' , result.stderr ) # save the streams A = variation.replace(' ' , '-' ) with open(Path(snake_case__ ) / F'log.{prefix}.stdout.txt' , 'w' ) as f: f.write(result.stdout ) with open(Path(snake_case__ ) / F'log.{prefix}.stderr.txt' , 'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(F'{output_dir}/all_results.json' , 'r' , encoding='utf-8' ) as f: A = json.load(snake_case__ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _snake_case ( snake_case__ : str , snake_case__ : str , snake_case__ : str , snake_case__ : List[str] , snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : Dict , snake_case__ : Optional[Any] , ): A = [] A = [] A = F'{id}: {variation:<{longest_variation_len}}' A = F'{preamble}: ' A = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(snake_case__ ) , desc=snake_case__ , leave=snake_case__ ): A = process_run_single( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) A = single_run_metrics[target_metric_key] if not math.isnan(snake_case__ ): metrics.append(snake_case__ ) results.append(snake_case__ ) outcome += "✓" else: outcome += "✘" A = F'\33[2K\r{outcome}' if len(snake_case__ ) > 0: A = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} A = round(mean_metrics[target_metric_key] , 2 ) A = F'{outcome} {mean_target}' if len(snake_case__ ) > 1: results_str += F' {tuple(round(snake_case__ , 2 ) for x in results )}' print(snake_case__ ) A = variation return mean_metrics else: print(snake_case__ ) return {variation_key: variation, target_metric_key: nan} def _snake_case ( ): A = torch.cuda.get_device_properties(torch.device('cuda' ) ) return F'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n' def _snake_case ( snake_case__ : List[str] , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Union[str, Any] ): A = pd.DataFrame(snake_case__ ) A = 'variation' A = 'diff_%' A = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan A = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(snake_case__ ): # as a fallback, use the minimal value as the sentinel A = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(snake_case__ ): A = df.apply( lambda snake_case__ : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='columns' , ) # re-order columns A = [variation_key, target_metric_key, diff_key, *report_metric_keys] A = df.reindex(snake_case__ , axis='columns' ) # reorder cols # capitalize A = df.rename(str.capitalize , axis='columns' ) # make the cols as narrow as possible A = df.rename(lambda snake_case__ : c.replace('_' , '<br>' ) , axis='columns' ) A = df.rename(lambda snake_case__ : c.replace('_' , '\n' ) , axis='columns' ) A = ['', 'Copy between the cut-here-lines and paste as is to github or a forum'] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=snake_case__ , floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=snake_case__ , floatfmt='.2f' )] print('\n\n'.join(snake_case__ ) ) def _snake_case ( ): A = argparse.ArgumentParser() parser.add_argument( '--base-cmd' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Base cmd' , ) parser.add_argument( '--variations' , default=snake_case__ , type=snake_case__ , nargs='+' , required=snake_case__ , help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' , ) parser.add_argument( '--base-variation' , default=snake_case__ , type=snake_case__ , help='Baseline variation to compare to. if None the minimal target value will be used to compare against' , ) parser.add_argument( '--target-metric-key' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' , ) parser.add_argument( '--report-metric-keys' , default='' , type=snake_case__ , help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' , ) parser.add_argument( '--repeat-times' , default=1 , type=snake_case__ , help='How many times to re-run each variation - an average will be reported' , ) parser.add_argument( '--output_dir' , default='output_benchmark' , type=snake_case__ , help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' , ) parser.add_argument( '--verbose' , default=snake_case__ , action='store_true' , help='Whether to show the outputs of each run or just the benchmark progress' , ) A = parser.parse_args() A = args.output_dir Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) A = get_base_command(snake_case__ , snake_case__ ) # split each dimension into its --foo variations A = [list(map(str.strip , re.split(r'\|' , snake_case__ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty A = list(map(str.strip , map(' '.join , itertools.product(*snake_case__ ) ) ) ) A = max(len(snake_case__ ) for x in variations ) # split wanted keys A = args.report_metric_keys.split() # capture prints into a log file for convenience A = F'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(F'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(F'and this script\'s output is also piped into {report_fn}' ) A = Tee(snake_case__ ) print(F'\n*** Running {len(snake_case__ )} benchmarks:' ) print(F'Base command: {" ".join(snake_case__ )}' ) A = 'variation' A = [] for id, variation in enumerate(tqdm(snake_case__ , desc='Total completion: ' , leave=snake_case__ ) ): A = base_cmd + variation.split() results.append( process_run( id + 1 , snake_case__ , snake_case__ , snake_case__ , snake_case__ , args.target_metric_key , snake_case__ , args.repeat_times , snake_case__ , args.verbose , ) ) process_results(snake_case__ , args.target_metric_key , snake_case__ , args.base_variation , snake_case__ ) if __name__ == "__main__": main()
91
0
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class __snake_case( unittest.TestCase ): '''simple docstring''' def __snake_case ( self ) -> Any: # A mock response for an HTTP head request to emulate server down lowerCAmelCase = mock.Mock() lowerCAmelCase = 500 lowerCAmelCase = {} lowerCAmelCase = HTTPError lowerCAmelCase = {} # Download this model to make sure it's in the cache. lowerCAmelCase = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("""requests.Session.request""" , return_value=A_ ) as mock_head: lowerCAmelCase = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def __snake_case ( self ) -> Optional[int]: # A mock response for an HTTP head request to emulate server down lowerCAmelCase = mock.Mock() lowerCAmelCase = 500 lowerCAmelCase = {} lowerCAmelCase = HTTPError lowerCAmelCase = {} # Download this model to make sure it's in the cache. lowerCAmelCase = GPTaTokenizerFast.from_pretrained("""gpt2""" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("""requests.Session.request""" , return_value=A_ ) as mock_head: lowerCAmelCase = GPTaTokenizerFast.from_pretrained("""gpt2""" ) # This check we did call the fake head request mock_head.assert_called() def __snake_case ( self ) -> int: # This test is for deprecated behavior and can be removed in v5 try: lowerCAmelCase = tempfile.mktemp() with open(A_ , """wb""" ) as f: http_get("""https://huggingface.co/albert-base-v1/resolve/main/spiece.model""" , A_ ) lowerCAmelCase = AlbertTokenizer.from_pretrained(A_ ) finally: os.remove(A_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile("""tokenizer.json""" ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open("""tokenizer.json""" , """wb""" ) as f: http_get("""https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json""" , A_ ) lowerCAmelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""" ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove("""tokenizer.json""" ) def __snake_case ( self ) -> Any: # This test is for deprecated behavior and can be removed in v5 lowerCAmelCase = AlbertTokenizer.from_pretrained("""https://huggingface.co/albert-base-v1/resolve/main/spiece.model""" ) @is_staging_test class __snake_case( unittest.TestCase ): '''simple docstring''' UpperCAmelCase : Optional[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def __snake_case ( cls ) -> Optional[Any]: lowerCAmelCase = TOKEN HfFolder.save_token(A_ ) @classmethod def __snake_case ( cls ) -> List[Any]: try: delete_repo(token=cls._token , repo_id="""test-tokenizer""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-tokenizer-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-tokenizer""" ) except HTTPError: pass def __snake_case ( self ) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = os.path.join(A_ , """vocab.txt""" ) with open(A_ , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) lowerCAmelCase = BertTokenizer(A_ ) tokenizer.push_to_hub("""test-tokenizer""" , use_auth_token=self._token ) lowerCAmelCase = BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="""test-tokenizer""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A_ , repo_id="""test-tokenizer""" , push_to_hub=A_ , use_auth_token=self._token ) lowerCAmelCase = BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def __snake_case ( self ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = os.path.join(A_ , """vocab.txt""" ) with open(A_ , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) lowerCAmelCase = BertTokenizer(A_ ) tokenizer.push_to_hub("""valid_org/test-tokenizer-org""" , use_auth_token=self._token ) lowerCAmelCase = BertTokenizer.from_pretrained("""valid_org/test-tokenizer-org""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-tokenizer-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( A_ , repo_id="""valid_org/test-tokenizer-org""" , push_to_hub=A_ , use_auth_token=self._token ) lowerCAmelCase = BertTokenizer.from_pretrained("""valid_org/test-tokenizer-org""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def __snake_case ( self ) -> List[str]: CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = os.path.join(A_ , """vocab.txt""" ) with open(A_ , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) lowerCAmelCase = CustomTokenizer(A_ ) # No fast custom tokenizer tokenizer.push_to_hub("""test-dynamic-tokenizer""" , use_auth_token=self._token ) lowerCAmelCase = AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' , trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , """CustomTokenizer""" ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = os.path.join(A_ , """vocab.txt""" ) with open(A_ , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) lowerCAmelCase = BertTokenizerFast.from_pretrained(A_ ) bert_tokenizer.save_pretrained(A_ ) lowerCAmelCase = CustomTokenizerFast.from_pretrained(A_ ) tokenizer.push_to_hub("""test-dynamic-tokenizer""" , use_auth_token=self._token ) lowerCAmelCase = AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' , trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , """CustomTokenizerFast""" ) lowerCAmelCase = AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' , use_fast=A_ , trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , """CustomTokenizer""" ) class __snake_case( unittest.TestCase ): '''simple docstring''' def __snake_case ( self ) -> Dict: lowerCAmelCase = Trie() trie.add("""Hello 友達""" ) self.assertEqual(trie.data , {"""H""": {"""e""": {"""l""": {"""l""": {"""o""": {""" """: {"""友""": {"""達""": {"""""": 1}}}}}}}}} ) trie.add("""Hello""" ) trie.data self.assertEqual(trie.data , {"""H""": {"""e""": {"""l""": {"""l""": {"""o""": {"""""": 1, """ """: {"""友""": {"""達""": {"""""": 1}}}}}}}}} ) def __snake_case ( self ) -> List[Any]: lowerCAmelCase = Trie() self.assertEqual(trie.split("""[CLS] This is a extra_id_100""" ) , ["""[CLS] This is a extra_id_100"""] ) trie.add("""[CLS]""" ) trie.add("""extra_id_1""" ) trie.add("""extra_id_100""" ) self.assertEqual(trie.split("""[CLS] This is a extra_id_100""" ) , ["""[CLS]""", """ This is a """, """extra_id_100"""] ) def __snake_case ( self ) -> List[str]: lowerCAmelCase = Trie() trie.add("""A""" ) self.assertEqual(trie.split("""ABC""" ) , ["""A""", """BC"""] ) self.assertEqual(trie.split("""BCA""" ) , ["""BC""", """A"""] ) def __snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = Trie() trie.add("""TOKEN]""" ) trie.add("""[SPECIAL_TOKEN]""" ) self.assertEqual(trie.split("""This is something [SPECIAL_TOKEN]""" ) , ["""This is something """, """[SPECIAL_TOKEN]"""] ) def __snake_case ( self ) -> Tuple: lowerCAmelCase = Trie() trie.add("""A""" ) trie.add("""P""" ) trie.add("""[SPECIAL_TOKEN]""" ) self.assertEqual(trie.split("""This is something [SPECIAL_TOKEN]""" ) , ["""This is something """, """[SPECIAL_TOKEN]"""] ) def __snake_case ( self ) -> int: lowerCAmelCase = Trie() trie.add("""AB""" ) trie.add("""B""" ) trie.add("""C""" ) self.assertEqual(trie.split("""ABC""" ) , ["""AB""", """C"""] ) def __snake_case ( self ) -> Optional[Any]: lowerCAmelCase = Trie() trie.add("""ABC""" ) trie.add("""B""" ) trie.add("""CD""" ) self.assertEqual(trie.split("""ABCD""" ) , ["""ABC""", """D"""] ) def __snake_case ( self ) -> List[str]: # Even if the offsets are wrong, we necessarily output correct string # parts. lowerCAmelCase = Trie() lowerCAmelCase = trie.cut_text("""ABC""" , [0, 0, 2, 1, 2, 3] ) self.assertEqual(A_ , ["""AB""", """C"""] )
433
"""simple docstring""" import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('''>=''', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType _lowercase = get_logger(__name__) def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : List[Any] , snake_case__ : int , snake_case__ : int , snake_case__ : str=0 ): os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A = os.path.join(snake_case__ , snake_case__ ) if accelerator.process_index == 0: logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A = os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving model to {ckpt_dir}' ) A = {'model': state_dict} dist_cp.save_state_dict( state_dict=snake_case__ , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Model saved to {ckpt_dir}' ) def _snake_case ( snake_case__ : int , snake_case__ : List[str] , snake_case__ : str , snake_case__ : str , snake_case__ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(snake_case__ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( 'Set the `sync_module_states` flag to `True` so that model states are synced across processes when ' 'initializing FSDP object' ) return A = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A = ( os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) if F'{MODEL_NAME}' not in input_dir else input_dir ) logger.info(F'Loading model from {ckpt_dir}' ) A = {'model': model.state_dict()} dist_cp.load_state_dict( state_dict=snake_case__ , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , planner=DefaultLoadPlanner() , ) A = state_dict['model'] logger.info(F'Model loaded from {ckpt_dir}' ) model.load_state_dict(snake_case__ ) def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int] , snake_case__ : Optional[int] , snake_case__ : Dict , snake_case__ : List[str] , snake_case__ : Any=0 ): os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A = FSDP.optim_state_dict(snake_case__ , snake_case__ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: A = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving Optimizer state to {output_optimizer_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Optimizer state saved in {output_optimizer_file}' ) else: A = os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving Optimizer state to {ckpt_dir}' ) dist_cp.save_state_dict( state_dict={'optimizer': optim_state} , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Optimizer state saved in {ckpt_dir}' ) def _snake_case ( snake_case__ : str , snake_case__ : Optional[int] , snake_case__ : List[str] , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Optional[int]=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: A = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading Optimizer state from {input_optimizer_file}' ) A = torch.load(snake_case__ ) logger.info(F'Optimizer state loaded from {input_optimizer_file}' ) else: A = ( os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) if F'{OPTIMIZER_NAME}' not in input_dir else input_dir ) logger.info(F'Loading Optimizer from {ckpt_dir}' ) A = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key='optimizer' , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , ) A = optim_state['optimizer'] logger.info(F'Optimizer loaded from {ckpt_dir}' ) A = FSDP.optim_state_dict_to_load(snake_case__ , snake_case__ , snake_case__ ) optimizer.load_state_dict(snake_case__ )
91
0
from queue import PriorityQueue from typing import Any import numpy as np def _UpperCAmelCase (UpperCamelCase__ : dict , UpperCamelCase__ : str , UpperCamelCase__ : set , UpperCamelCase__ : set , UpperCamelCase__ : dict , UpperCamelCase__ : dict , UpperCamelCase__ : PriorityQueue , UpperCamelCase__ : dict , UpperCamelCase__ : float | int , ): for nxt, d in graph[v]: if nxt in visited_forward: continue _A : int = cst_fwd.get(snake_case__ , np.inf ) _A : str = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) _A : Optional[Any] = new_cost_f _A : List[Any] = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: _A : List[Any] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _UpperCAmelCase (UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : dict , UpperCamelCase__ : dict ): _A : str = -1 _A : Tuple = set() _A : Union[str, Any] = set() _A : List[str] = {source: 0} _A : Dict = {destination: 0} _A : Tuple = {source: None} _A : List[str] = {destination: None} _A : Optional[int] = PriorityQueue() _A : Union[str, Any] = PriorityQueue() _A : Any = 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(): _A , _A : int = queue_forward.get() visited_forward.add(snake_case__ ) _A , _A : List[str] = queue_backward.get() visited_backward.add(snake_case__ ) _A : Optional[int] = pass_and_relaxation( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ) _A : Any = pass_and_relaxation( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: _A : Dict = shortest_distance return shortest_path_distance lowerCAmelCase__ = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } lowerCAmelCase__ = { '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()
503
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: str = AudioLDMPipeline _lowerCamelCase: Optional[int] = TEXT_TO_AUDIO_PARAMS _lowerCamelCase: Optional[int] = TEXT_TO_AUDIO_BATCH_PARAMS _lowerCamelCase: Optional[int] = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=(32, 64) ,class_embed_type='simple_projection' ,projection_class_embeddings_input_dim=32 ,class_embeddings_concat=A_ ,) A = DDIMScheduler( beta_start=0.0_00_85 ,beta_end=0.0_12 ,beta_schedule='scaled_linear' ,clip_sample=A_ ,set_alpha_to_one=A_ ,) torch.manual_seed(0 ) A = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=1 ,out_channels=1 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) torch.manual_seed(0 ) A = ClapTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,projection_dim=32 ,) A = ClapTextModelWithProjection(A_ ) A = RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta' ,model_max_length=77 ) A = SpeechTaHifiGanConfig( model_in_dim=8 ,sampling_rate=1_6000 ,upsample_initial_channel=16 ,upsample_rates=[2, 2] ,upsample_kernel_sizes=[4, 4] ,resblock_kernel_sizes=[3, 7] ,resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] ,normalize_before=A_ ,) A = SpeechTaHifiGan(A_ ) A = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'vocoder': vocoder, } return components def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Dict=0 ) -> str: if str(A_ ).startswith('mps' ): A = torch.manual_seed(A_ ) else: A = torch.Generator(device=A_ ).manual_seed(A_ ) A = { 'prompt': 'A hammer hitting a wooden surface', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, } return inputs def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = audioldm_pipe(**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) == 256 A = audio[:10] A = np.array( [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 3 * [inputs['prompt']] # forward A = audioldm_pipe(**A_ ) A = output.audios[0] A = self.get_dummy_inputs(A_ ) A = 3 * [inputs.pop('prompt' )] A = audioldm_pipe.tokenizer( A_ ,padding='max_length' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=A_ ,return_tensors='pt' ,) A = text_inputs['input_ids'].to(A_ ) A = audioldm_pipe.text_encoder( A_ ,) A = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state A = F.normalize(A_ ,dim=-1 ) A = prompt_embeds # forward A = audioldm_pipe(**A_ ) A = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 3 * ['this is a negative prompt'] A = negative_prompt A = 3 * [inputs['prompt']] # forward A = audioldm_pipe(**A_ ) A = output.audios[0] A = self.get_dummy_inputs(A_ ) A = 3 * [inputs.pop('prompt' )] A = [] for p in [prompt, negative_prompt]: A = audioldm_pipe.tokenizer( A_ ,padding='max_length' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=A_ ,return_tensors='pt' ,) A = text_inputs['input_ids'].to(A_ ) A = audioldm_pipe.text_encoder( A_ ,) A = text_embeds.text_embeds # additional L_2 normalization over each hidden-state A = F.normalize(A_ ,dim=-1 ) embeds.append(A_ ) A , A = embeds # forward A = audioldm_pipe(**A_ ) A = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = PNDMScheduler(skip_prk_steps=A_ ) A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 'egg cracking' A = audioldm_pipe(**A_ ,negative_prompt=A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) == 256 A = audio[:10] A = np.array( [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = PNDMScheduler(skip_prk_steps=A_ ) A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = 'A hammer hitting a wooden surface' # test num_waveforms_per_prompt=1 (default) A = audioldm_pipe(A_ ,num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts A = 2 A = audioldm_pipe([prompt] * batch_size ,num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt A = 2 A = audioldm_pipe(A_ ,num_inference_steps=2 ,num_waveforms_per_prompt=A_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts A = 2 A = audioldm_pipe( [prompt] * batch_size ,num_inference_steps=2 ,num_waveforms_per_prompt=A_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = audioldm_pipe.vocoder.config.sampling_rate A = self.get_dummy_inputs(A_ ) A = audioldm_pipe(audio_length_in_s=0.0_16 ,**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) / vocoder_sampling_rate == 0.0_16 A = audioldm_pipe(audio_length_in_s=0.0_32 ,**A_ ) A = output.audios[0] assert audio.ndim == 1 assert len(A_ ) / vocoder_sampling_rate == 0.0_32 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: A = self.get_dummy_components() A = AudioLDMPipeline(**A_ ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = ['hey'] A = audioldm_pipe(A_ ,num_inference_steps=1 ) A = output.audios.shape assert audio_shape == (1, 256) A = audioldm_pipe.vocoder.config config.model_in_dim *= 2 A = SpeechTaHifiGan(A_ ).to(A_ ) A = audioldm_pipe(A_ ,num_inference_steps=1 ) A = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: self._test_inference_batch_single_identical(test_mean_pixel_difference=A_ ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() ,reason='XFormers attention is only available with CUDA and `xformers` installed' ,) def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A_ ) @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[Any] ,A_ : str="cpu" ,A_ : List[str]=torch.floataa ,A_ : str=0 ) -> List[Any]: A = torch.Generator(device=A_ ).manual_seed(A_ ) A = np.random.RandomState(A_ ).standard_normal((1, 8, 128, 16) ) A = torch.from_numpy(A_ ).to(device=A_ ,dtype=A_ ) A = { 'prompt': 'A hammer hitting a wooden surface', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 2.5, } return inputs def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_inputs(A_ ) A = 25 A = audioldm_pipe(**A_ ).audios[0] assert audio.ndim == 1 assert len(A_ ) == 8_1920 A = audio[7_7230:7_7240] A = np.array( [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15] ) A = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: A = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) A = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) A = audioldm_pipe.to(A_ ) audioldm_pipe.set_progress_bar_config(disable=A_ ) A = self.get_inputs(A_ ) A = audioldm_pipe(**A_ ).audios[0] assert audio.ndim == 1 assert len(A_ ) == 8_1920 A = audio[2_7780:2_7790] A = np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12] ) A = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
91
0
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[str]] , lowerCAmelCase__ : int , ) -> List[Any]: __a = len(snake_case__ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(snake_case__ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , snake_case__ , snake_case__ , ) def lowercase ( lowerCAmelCase__ : int ) -> Tuple: __a = [] depth_first_search([] , [] , [] , snake_case__ , snake_case__ ) # Print all the boards for board in boards: for column in board: print(snake_case__ ) print('''''' ) print(len(snake_case__ ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
695
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
91
0
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property 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 import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase_ : """simple docstring""" def __init__( self :List[str] , lowerCamelCase__ :Union[str, Any] , lowerCamelCase__ :str=2 , lowerCamelCase__ :Union[str, Any]=3 , lowerCamelCase__ :Dict=4 , lowerCamelCase__ :Optional[Any]=2 , lowerCamelCase__ :Any=7 , lowerCamelCase__ :Any=True , lowerCamelCase__ :List[str]=True , lowerCamelCase__ :Tuple=True , lowerCamelCase__ :Optional[int]=True , lowerCamelCase__ :Dict=99 , lowerCamelCase__ :int=36 , lowerCamelCase__ :Dict=2 , lowerCamelCase__ :Tuple=4 , lowerCamelCase__ :List[Any]=37 , lowerCamelCase__ :int="gelu" , lowerCamelCase__ :Tuple=0.1 , lowerCamelCase__ :Union[str, Any]=0.1 , lowerCamelCase__ :Optional[int]=5_12 , lowerCamelCase__ :Dict=16 , lowerCamelCase__ :Dict=2 , lowerCamelCase__ :int=0.02 , lowerCamelCase__ :Dict=6 , lowerCamelCase__ :Dict=6 , lowerCamelCase__ :int=3 , lowerCamelCase__ :str=4 , lowerCamelCase__ :List[Any]=None , lowerCamelCase__ :str=10_00 , ): UpperCamelCase__ :Dict = parent UpperCamelCase__ :Union[str, Any] = batch_size UpperCamelCase__ :List[Any] = num_channels UpperCamelCase__ :Tuple = image_size UpperCamelCase__ :int = patch_size UpperCamelCase__ :List[Any] = is_training UpperCamelCase__ :Any = use_input_mask UpperCamelCase__ :List[str] = use_token_type_ids UpperCamelCase__ :Any = use_labels UpperCamelCase__ :Any = vocab_size UpperCamelCase__ :Tuple = hidden_size UpperCamelCase__ :List[str] = num_hidden_layers UpperCamelCase__ :Optional[int] = num_attention_heads UpperCamelCase__ :List[str] = intermediate_size UpperCamelCase__ :Union[str, Any] = hidden_act UpperCamelCase__ :Union[str, Any] = hidden_dropout_prob UpperCamelCase__ :List[Any] = attention_probs_dropout_prob UpperCamelCase__ :int = max_position_embeddings UpperCamelCase__ :Union[str, Any] = type_vocab_size UpperCamelCase__ :List[Any] = type_sequence_label_size UpperCamelCase__ :str = initializer_range UpperCamelCase__ :List[Any] = coordinate_size UpperCamelCase__ :Dict = shape_size UpperCamelCase__ :List[Any] = num_labels UpperCamelCase__ :Any = num_choices UpperCamelCase__ :List[str] = scope UpperCamelCase__ :Dict = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) UpperCamelCase__ :Dict = text_seq_length UpperCamelCase__ :Union[str, Any] = (image_size // patch_size) ** 2 + 1 UpperCamelCase__ :List[Any] = self.text_seq_length + self.image_seq_length def __a ( self :Union[str, Any] ): UpperCamelCase__ :str = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) UpperCamelCase__ :Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) UpperCamelCase__ :Optional[int] = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase__ :List[str] = bbox[i, j, 3] UpperCamelCase__ :str = bbox[i, j, 1] UpperCamelCase__ :Any = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase__ :Optional[int] = bbox[i, j, 2] UpperCamelCase__ :Dict = bbox[i, j, 0] UpperCamelCase__ :Tuple = tmp_coordinate UpperCamelCase__ :int = tf.constant(A_ ) UpperCamelCase__ :List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ :int = None if self.use_input_mask: UpperCamelCase__ :List[str] = random_attention_mask([self.batch_size, self.text_seq_length] ) UpperCamelCase__ :int = None if self.use_token_type_ids: UpperCamelCase__ :Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) UpperCamelCase__ :List[str] = None UpperCamelCase__ :Optional[int] = None if self.use_labels: UpperCamelCase__ :Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ :Tuple = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) UpperCamelCase__ :Union[str, Any] = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __a ( self :List[str] , lowerCamelCase__ :Optional[int] , lowerCamelCase__ :Dict , lowerCamelCase__ :Optional[Any] , lowerCamelCase__ :Optional[int] , lowerCamelCase__ :Optional[int] , lowerCamelCase__ :Tuple ): UpperCamelCase__ :List[str] = TFLayoutLMvaModel(config=A_ ) # text + image UpperCamelCase__ :int = model(A_ , pixel_values=A_ , training=A_ ) UpperCamelCase__ :Tuple = model( A_ , bbox=A_ , pixel_values=A_ , attention_mask=A_ , token_type_ids=A_ , training=A_ , ) UpperCamelCase__ :Tuple = model(A_ , bbox=A_ , pixel_values=A_ , training=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only UpperCamelCase__ :str = model(A_ , training=A_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only UpperCamelCase__ :Optional[Any] = model({"""pixel_values""": pixel_values} , training=A_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __a ( self :int , lowerCamelCase__ :List[Any] , lowerCamelCase__ :Any , lowerCamelCase__ :str , lowerCamelCase__ :str , lowerCamelCase__ :List[str] , lowerCamelCase__ :Optional[Any] , lowerCamelCase__ :List[str] ): UpperCamelCase__ :List[str] = self.num_labels UpperCamelCase__ :Optional[Any] = TFLayoutLMvaForSequenceClassification(config=A_ ) UpperCamelCase__ :List[Any] = model( A_ , bbox=A_ , pixel_values=A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ , training=A_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __a ( self :List[str] , lowerCamelCase__ :List[str] , lowerCamelCase__ :Any , lowerCamelCase__ :List[Any] , lowerCamelCase__ :List[str] , lowerCamelCase__ :List[Any] , lowerCamelCase__ :Union[str, Any] , lowerCamelCase__ :List[Any] ): UpperCamelCase__ :Optional[Any] = self.num_labels UpperCamelCase__ :List[str] = TFLayoutLMvaForTokenClassification(config=A_ ) UpperCamelCase__ :List[Any] = model( A_ , bbox=A_ , pixel_values=A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ , training=A_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __a ( self :List[Any] , lowerCamelCase__ :int , lowerCamelCase__ :List[str] , lowerCamelCase__ :Tuple , lowerCamelCase__ :List[str] , lowerCamelCase__ :Optional[int] , lowerCamelCase__ :Optional[int] , lowerCamelCase__ :Optional[Any] ): UpperCamelCase__ :List[Any] = 2 UpperCamelCase__ :str = TFLayoutLMvaForQuestionAnswering(config=A_ ) UpperCamelCase__ :Dict = model( A_ , bbox=A_ , pixel_values=A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , training=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 :List[str] ): UpperCamelCase__ :Tuple = self.prepare_config_and_inputs() ((UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__)) :str = config_and_inputs UpperCamelCase__ :Union[str, Any] = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): """simple docstring""" _snake_case : str = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _snake_case : int = ( {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel} if is_tf_available() else {} ) _snake_case : int = False _snake_case : Any = False _snake_case : Any = False def __a ( self :Any , lowerCamelCase__ :Tuple , lowerCamelCase__ :Any , lowerCamelCase__ :Optional[int] , lowerCamelCase__ :Dict , lowerCamelCase__ :Dict ): return True def __a ( self :Union[str, Any] , lowerCamelCase__ :int , lowerCamelCase__ :Tuple , lowerCamelCase__ :Optional[int]=False ): UpperCamelCase__ :Dict = copy.deepcopy(A_ ) if model_class in get_values(A_ ): UpperCamelCase__ :Optional[int] = { k: tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(A_ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A_ ): UpperCamelCase__ :Optional[int] = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(A_ ): UpperCamelCase__ :List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) UpperCamelCase__ :Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(A_ ): UpperCamelCase__ :List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(A_ ): UpperCamelCase__ :str = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __a ( self :List[Any] ): UpperCamelCase__ :List[str] = TFLayoutLMvaModelTester(self ) UpperCamelCase__ :int = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __a ( self :Dict ): self.config_tester.run_common_tests() def __a ( self :Any ): UpperCamelCase__ , UpperCamelCase__ :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ :int = model_class(A_ ) if getattr(A_ , """hf_compute_loss""" , A_ ): # The number of elements in the loss should be the same as the number of elements in the label UpperCamelCase__ :str = self._prepare_for_class(inputs_dict.copy() , A_ , return_labels=A_ ) UpperCamelCase__ :List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=A_ )[0] ] UpperCamelCase__ :str = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs UpperCamelCase__ :str = self._prepare_for_class(inputs_dict.copy() , A_ , return_labels=A_ ) UpperCamelCase__ :Optional[int] = prepared_for_class.pop("""input_ids""" ) UpperCamelCase__ :List[str] = model(A_ , **A_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions UpperCamelCase__ :int = self._prepare_for_class(inputs_dict.copy() , A_ , return_labels=A_ ) UpperCamelCase__ :str = prepared_for_class.pop("""input_ids""" ) if "labels" in prepared_for_class: UpperCamelCase__ :int = prepared_for_class["""labels"""].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: UpperCamelCase__ :Union[str, Any] = -1_00 UpperCamelCase__ :List[str] = tf.convert_to_tensor(A_ ) UpperCamelCase__ :int = model(A_ , **A_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict UpperCamelCase__ :Optional[Any] = self._prepare_for_class(inputs_dict.copy() , A_ , return_labels=A_ ) UpperCamelCase__ :List[str] = model(A_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple UpperCamelCase__ :str = self._prepare_for_class(inputs_dict.copy() , A_ , return_labels=A_ ) # Get keys that were added with the _prepare_for_class function UpperCamelCase__ :Any = prepared_for_class.keys() - inputs_dict.keys() UpperCamelCase__ :int = inspect.signature(model.call ).parameters UpperCamelCase__ :int = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple UpperCamelCase__ :int = {0: """input_ids"""} for label_key in label_keys: UpperCamelCase__ :int = signature_names.index(A_ ) UpperCamelCase__ :Tuple = label_key UpperCamelCase__ :Optional[int] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple UpperCamelCase__ :List[Any] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: UpperCamelCase__ :List[Any] = prepared_for_class[value] UpperCamelCase__ :Dict = tuple(A_ ) # Send to model UpperCamelCase__ :str = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __a ( self :List[str] ): ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(A_ , A_ , A_ , A_ , A_ , A_ ) def __a ( self :Optional[Any] ): ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) :Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ :Optional[Any] = type self.model_tester.create_and_check_model(A_ , A_ , A_ , A_ , A_ , A_ ) def __a ( self :Tuple ): ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( A_ , A_ , A_ , A_ , A_ , A_ , A_ ) def __a ( self :Dict ): ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( A_ , A_ , A_ , A_ , A_ , A_ , A_ ) def __a ( self :str ): ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( A_ , A_ , A_ , A_ , A_ , A_ , A_ ) @slow def __a ( self :int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ :Tuple = TFLayoutLMvaModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def A ( ) -> Optional[int]: UpperCamelCase__ :Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def __a ( self :int ): return LayoutLMvaImageProcessor(apply_ocr=A_ ) if is_vision_available() else None @slow def __a ( self :Tuple ): UpperCamelCase__ :int = TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ) UpperCamelCase__ :List[Any] = self.default_image_processor UpperCamelCase__ :Optional[Any] = prepare_img() UpperCamelCase__ :int = image_processor(images=A_ , return_tensors="""tf""" ).pixel_values UpperCamelCase__ :Tuple = tf.constant([[1, 2]] ) UpperCamelCase__ :List[str] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass UpperCamelCase__ :Optional[Any] = model(input_ids=A_ , bbox=A_ , pixel_values=A_ , training=A_ ) # verify the logits UpperCamelCase__ :Dict = (1, 1_99, 7_68) self.assertEqual(outputs.last_hidden_state.shape , A_ ) UpperCamelCase__ :Union[str, Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , A_ , atol=1e-4 ) )
45
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def _snake_case ( ): A = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A = get_sagemaker_input() else: A = get_cluster_input() return config def _snake_case ( snake_case__ : Any=None ): if subparsers is not None: A = subparsers.add_parser('config' , description=snake_case__ ) else: A = argparse.ArgumentParser('Accelerate config command' , description=snake_case__ ) parser.add_argument( '--config_file' , default=snake_case__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=snake_case__ ) return parser def _snake_case ( snake_case__ : Tuple ): A = get_user_input() if args.config_file is not None: A = args.config_file else: if not os.path.isdir(snake_case__ ): os.makedirs(snake_case__ ) A = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(snake_case__ ) else: config.to_yaml_file(snake_case__ ) print(F'accelerate configuration saved at {config_file}' ) def _snake_case ( ): A = config_command_parser() A = parser.parse_args() config_command(snake_case__ ) if __name__ == "__main__": main()
91
0
"""simple docstring""" import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A = logging.get_logger(__name__) __A = {'''vocab_file''': '''spiece.model'''} __A = { '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } __A = { '''AI-Sweden/gpt-sw3-126m''': 2048, '''AI-Sweden/gpt-sw3-350m''': 2048, '''AI-Sweden/gpt-sw3-1.6b''': 2048, '''AI-Sweden/gpt-sw3-6.7b''': 2048, '''AI-Sweden/gpt-sw3-20b''': 2048, } class _snake_case ( _lowercase ): snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Tuple , UpperCAmelCase : Any , UpperCAmelCase : int=False , UpperCAmelCase : List[Any]=False , UpperCAmelCase : Optional[int]=False , UpperCAmelCase : Union[str, Any]=None , UpperCAmelCase : Tuple=None , UpperCAmelCase : Any=None , UpperCAmelCase : int=None , UpperCAmelCase : Optional[Dict[str, Any]] = None , **UpperCAmelCase : Tuple , ): __lowerCamelCase : Dict = {} if sp_model_kwargs is None else sp_model_kwargs __lowerCamelCase : List[Any] = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) __lowerCamelCase : Optional[int] = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __lowerCamelCase : Any = "<|endoftext|>" if eos_token is None else eos_token __lowerCamelCase : Union[str, Any] = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __lowerCamelCase : int = unk_token if pad_token is None else pad_token __lowerCamelCase : Optional[int] = eos_token if bos_token is None else bos_token else: __lowerCamelCase : Tuple = "<pad>" if pad_token is None else pad_token __lowerCamelCase : Tuple = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=A_ , remove_space=A_ , keep_accents=A_ , bos_token=A_ , eos_token=A_ , unk_token=A_ , pad_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __lowerCamelCase : int = do_lower_case __lowerCamelCase : List[str] = remove_space __lowerCamelCase : Optional[int] = keep_accents __lowerCamelCase : List[str] = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) # Used for whitespace normalization in input texts # fmt : off __lowerCamelCase : Optional[Any] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __lowerCamelCase : int = re.compile( F"""[{"".join(map(A_ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]""" ) def __getstate__( self : Optional[Any] ): __lowerCamelCase : Any = self.__dict__.copy() __lowerCamelCase : Dict = None return state def __setstate__( self : Dict , UpperCAmelCase : List[str] ): __lowerCamelCase : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __lowerCamelCase : Optional[int] = {} __lowerCamelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def lowerCamelCase__ ( self : Union[str, Any] ): return len(self.sp_model ) def lowerCamelCase__ ( self : Dict , UpperCAmelCase : str ): __lowerCamelCase : Any = self.non_printing_characters_re.sub("" , A_ ) # Normalize whitespaces __lowerCamelCase : str = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization __lowerCamelCase : Any = unicodedata.normalize("NFC" , A_ ) return text def lowerCamelCase__ ( self : Any , UpperCAmelCase : str , **UpperCAmelCase : Any ): __lowerCamelCase : Optional[int] = self.preprocess_text(A_ ) return self.sp_model.encode(A_ , out_type=A_ ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : str ): return self.sp_model.PieceToId(A_ ) def lowerCamelCase__ ( self : Any , UpperCAmelCase : int ): return self.sp_model.IdToPiece(A_ ) @staticmethod def lowerCamelCase__ ( UpperCAmelCase : str ): return out_string def lowerCamelCase__ ( self : Optional[Any] , UpperCAmelCase : List[str] ): __lowerCamelCase : Any = [] __lowerCamelCase : Dict = "" __lowerCamelCase : Any = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A_ ) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : int = [] else: current_sub_tokens.append(A_ ) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(A_ ) return out_string def lowerCamelCase__ ( self : Tuple ): __lowerCamelCase : List[str] = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase__ ( self : str , UpperCAmelCase : str , UpperCAmelCase : Optional[str] = None ): if not os.path.isdir(A_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase : Optional[Any] = os.path.join( A_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , "wb" ) as fi: __lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,) def lowerCamelCase__ ( self : Optional[int] , UpperCAmelCase : Union[str, List[str]] , UpperCAmelCase : Union[str, bool] = False ): if isinstance(A_ , A_ ): __lowerCamelCase : Union[str, Any] = self.preprocess_text(A_ ) __lowerCamelCase : List[str] = self.sp_model.encode(A_ ) else: __lowerCamelCase : int = [self.preprocess_text(A_ ) for t in text] __lowerCamelCase : Union[str, Any] = self.sp_model.encode(A_ ) if return_tensors is True or return_tensors == "pt": __lowerCamelCase : Dict = torch.tensor(A_ ) return token_ids def lowerCamelCase__ ( self : List[Any] , UpperCAmelCase : Union[int, List[int]] ): return self.sp_model.decode(A_ ) def lowerCamelCase__ ( self : Optional[Any] , UpperCAmelCase : "Conversation" ): __lowerCamelCase : List[str] = [F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()] __lowerCamelCase : List[Any] = ( F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(A_ ) + F"""{self.bos_token}Bot:""" ) return self.encode(text=A_ )
646
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : Any ,A_ : int=13 ,A_ : str=7 ,A_ : Tuple=True ,A_ : str=True ,A_ : str=False ,A_ : List[str]=True ,A_ : str=99 ,A_ : str=32 ,A_ : Optional[int]=5 ,A_ : Optional[Any]=4 ,A_ : str=37 ,A_ : Optional[Any]="gelu" ,A_ : Union[str, Any]=0.1 ,A_ : Any=0.1 ,A_ : Optional[Any]=512 ,A_ : str=16 ,A_ : int=2 ,A_ : Optional[Any]=0.02 ,A_ : str=3 ,A_ : str=4 ,A_ : List[str]=None ,) -> str: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = scope def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: return LlamaConfig( 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : Optional[int] ,A_ : Any ,A_ : Optional[Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ) -> List[Any]: A = LlamaModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : int ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Dict ,) -> List[str]: A = True A = LlamaModel(A_ ) model.to(A_ ) model.eval() A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,) A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict ,A_ : Dict ,A_ : Tuple ,A_ : Tuple ,A_ : Dict ,) -> Union[str, Any]: A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Dict ,A_ : Any ,A_ : int ,A_ : List[str] ,A_ : Tuple ,A_ : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : int ,) -> List[Any]: A = True A = True A = LlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() # first forward pass A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,use_cache=A_ ,) A = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A = ids_tensor((self.batch_size, 3) ,config.vocab_size ) A = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and A = torch.cat([input_ids, next_tokens] ,dim=-1 ) A = torch.cat([input_mask, next_mask] ,dim=-1 ) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,past_key_values=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] # select random slice A = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A = output_from_no_past[:, -3:, random_slice_idx].detach() A = 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 _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _lowerCamelCase: List[Any] = (LlamaForCausalLM,) if is_torch_available() else () _lowerCamelCase: Any = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) _lowerCamelCase: int = False _lowerCamelCase: List[str] = False def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = LlamaModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A = type self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'single_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = 'multi_label_classification' A = input_dict['input_ids'] A = input_ids.ne(1 ).to(A_ ) A = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) A = LlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ) -> str: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = ids_tensor([1, 10] ,config.vocab_size ) A = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = LlamaModel(A_ ) original_model.to(A_ ) original_model.eval() A = original_model(A_ ).last_hidden_state A = original_model(A_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A = {'type': scaling_type, 'factor': 10.0} A = LlamaModel(A_ ) scaled_model.to(A_ ) scaled_model.eval() A = scaled_model(A_ ).last_hidden_state A = scaled_model(A_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(A_ ,A_ ,atol=1e-5 ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' ,device_map='auto' ) A = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 A = torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) # Expected mean on dim = -1 A = torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]] ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A = torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: A = [1, 306, 4658, 278, 6593, 310, 2834, 338] A = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' ,device_map='auto' ) A = model(torch.tensor(A_ ) ) A = torch.tensor( [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,A_ ,atol=1e-2 ,rtol=1e-2 ) # fmt: off A = torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,A_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' A = 'Simply put, the theory of relativity states that ' A = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) A = tokenizer.encode(A_ ,return_tensors='pt' ) A = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' ,device_map='sequential' ,use_safetensors=A_ ) # greedy generation outputs A = model.generate(A_ ,max_new_tokens=64 ,top_p=A_ ,temperature=1 ,do_sample=A_ ) A = tokenizer.decode(generated_ids[0] ,skip_special_tokens=A_ ) self.assertEqual(A_ ,A_ )
91
0
'''simple docstring''' from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeling_tf_common import floats_tensor from .test_framework_agnostic import GenerationIntegrationTestsMixin if is_tf_available(): import tensorflow as tf from transformers import ( AutoTokenizer, TFAutoModelForCausalLM, TFAutoModelForSeqaSeqLM, TFAutoModelForSpeechSeqaSeq, TFAutoModelForVisionaSeq, TFBartForConditionalGeneration, TFLogitsProcessorList, TFMinLengthLogitsProcessor, tf_top_k_top_p_filtering, ) if is_tensorflow_text_available(): import tensorflow_text as text @require_tf class __lowercase ( unittest.TestCase ): def UpperCamelCase__ ( self ) -> Union[str, Any]: __a = tf.convert_to_tensor( [ [ 8.2_220_991, # 3rd highest value; idx. 0 -0.5_620_044, 5.23_229_752, 4.0_386_393, -6.8_798_378, -0.54_785_802, -3.2_012_153, 2.92_777_176, 1.88_171_953, 7.35_341_276, # 5th highest value; idx. 9 8.43_207_833, # 2nd highest value; idx. 10 -9.85_711_836, -5.96_209_236, -1.13_039_161, -7.1_115_294, -0.8_369_633, -5.3_186_408, 7.06_427_407, 0.81_369_344, -0.82_023_817, -5.9_179_796, 0.58_813_443, -6.99_778_438, 4.71_551_189, -0.18_771_637, 7.44_020_759, # 4th highest value; idx. 25 9.38_450_987, # 1st highest value; idx. 26 2.12_662_941, -9.32_562_038, 2.35_652_522, ], # cummulative prob of 5 highest values <= 0.6 [ 0.58_425_518, 4.53_139_238, -5.57_510_464, -6.28_030_699, -7.19_529_503, -4.02_122_551, 1.39_337_037, -6.06_707_057, 1.59_480_517, -9.643_119, 0.03_907_799, 0.67_231_762, -8.88_206_726, 6.27_115_922, # 4th highest value; idx. 13 2.28_520_723, 4.82_767_506, 4.30_421_368, 8.8_275_313, # 2nd highest value; idx. 17 5.44_029_958, # 5th highest value; idx. 18 -4.4_735_794, 7.38_579_536, # 3rd highest value; idx. 20 -2.91_051_663, 2.61_946_077, -2.5_674_762, -9.48_959_302, -4.02_922_645, -1.35_416_918, 9.67_702_323, # 1st highest value; idx. 27 -5.89_478_553, 1.85_370_467, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) __a = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above __a = tf.convert_to_tensor( [8.222_099, 7.3_534_126, 8.432_078, 7.4_402_075, 9.38_451, 6.271_159, 8.827_531, 5.4_402_995, 7.3_857_956, 9.677_023] , dtype=tf.floataa , ) # expected non filtered values as noted above __a = tf_top_k_top_p_filtering(A_ , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 ) __a = output[output != -float('inf' )] __a = tf.cast( tf.where(tf.not_equal(A_ , tf.constant(-float('inf' ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(A_ , A_ , rtol=1e-12 ) tf.debugging.assert_equal(A_ , A_ ) @require_tf class __lowercase ( unittest.TestCase , _lowercase ): if is_tf_available(): _a = { '''AutoModelForCausalLM''': TFAutoModelForCausalLM, '''AutoModelForSpeechSeq2Seq''': TFAutoModelForSpeechSeqaSeq, '''AutoModelForSeq2SeqLM''': TFAutoModelForSeqaSeqLM, '''AutoModelForVision2Seq''': TFAutoModelForVisionaSeq, '''LogitsProcessorList''': TFLogitsProcessorList, '''MinLengthLogitsProcessor''': TFMinLengthLogitsProcessor, '''create_tensor_fn''': tf.convert_to_tensor, '''floats_tensor''': floats_tensor, '''return_tensors''': '''tf''', } @slow def UpperCamelCase__ ( self ) -> Optional[Any]: # TF-only test: tf.saved_model export __a = TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __a = 2 __a = 2 class __lowercase ( tf.Module ): def __init__( self , UpperCamelCase ) -> Any: super(A_ , self ).__init__() __a = model @tf.function( input_signature=( tf.TensorSpec((None, input_length) , tf.intaa , name='input_ids' ), tf.TensorSpec((None, input_length) , tf.intaa , name='attention_mask' ), ) , jit_compile=A_ , ) def UpperCamelCase__ ( self , UpperCamelCase , UpperCamelCase ) -> Dict: __a = self.model.generate( input_ids=A_ , attention_mask=A_ , max_new_tokens=A_ , return_dict_in_generate=A_ , ) return {"sequences": outputs["sequences"]} __a = [[2, 0], [102, 103]] __a = [[1, 0], [1, 1]] __a = DummyModel(model=A_ ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(A_ , A_ , signatures={'serving_default': dummy_model.serving} ) __a = tf.saved_model.load(A_ ).signatures['serving_default'] for batch_size in range(1 , len(A_ ) + 1 ): __a = { 'input_ids': tf.constant(dummy_input_ids[:batch_size] ), 'attention_mask': tf.constant(dummy_attention_masks[:batch_size] ), } __a = serving_func(**A_ )['sequences'] __a = test_model.generate(**A_ , max_new_tokens=A_ ) tf.debugging.assert_equal(A_ , A_ ) @slow def UpperCamelCase__ ( self ) -> Optional[Any]: # TF-only test: tf.saved_model export __a = TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __a = 1 __a = 2 class __lowercase ( tf.Module ): def __init__( self , UpperCamelCase ) -> int: super(A_ , self ).__init__() __a = model @tf.function( input_signature=( tf.TensorSpec((batch_size, None) , tf.intaa , name='input_ids' ), tf.TensorSpec((batch_size, None) , tf.intaa , name='attention_mask' ), ) , jit_compile=A_ , ) def UpperCamelCase__ ( self , UpperCamelCase , UpperCamelCase ) -> List[str]: __a = self.model.generate( input_ids=A_ , attention_mask=A_ , max_new_tokens=A_ , return_dict_in_generate=A_ , ) return {"sequences": outputs["sequences"]} __a = [[2], [102, 103]] __a = [[1], [1, 1]] __a = DummyModel(model=A_ ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(A_ , A_ , signatures={'serving_default': dummy_model.serving} ) __a = tf.saved_model.load(A_ ).signatures['serving_default'] for input_row in range(len(A_ ) ): __a = { 'input_ids': tf.constant([dummy_input_ids[input_row]] ), 'attention_mask': tf.constant([dummy_attention_masks[input_row]] ), } __a = serving_func(**A_ )['sequences'] __a = test_model.generate(**A_ , max_new_tokens=A_ ) tf.debugging.assert_equal(A_ , A_ ) @slow @require_tensorflow_text def UpperCamelCase__ ( self ) -> Optional[int]: # TF-only test: tf.saved_model export with tempfile.TemporaryDirectory() as tmp_dir: # file needed to load the TF tokenizer hf_hub_download(repo_id='google/flan-t5-small' , filename='spiece.model' , local_dir=A_ ) class __lowercase ( tf.keras.layers.Layer ): def __init__( self ) -> Tuple: super().__init__() __a = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(A_ , 'spiece.model' ) , 'rb' ).read() ) __a = TFAutoModelForSeqaSeqLM.from_pretrained('hf-internal-testing/tiny-random-t5' ) def UpperCamelCase__ ( self , UpperCamelCase , *UpperCamelCase , **UpperCamelCase ) -> Union[str, Any]: __a = self.tokenizer.tokenize(A_ ) __a , __a = text.pad_model_inputs( A_ , max_seq_length=64 , pad_value=self.model.config.pad_token_id ) __a = self.model.generate(input_ids=A_ , attention_mask=A_ ) return self.tokenizer.detokenize(A_ ) __a = CompleteSentenceTransformer() __a = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name='inputs' ) __a = complete_model(A_ ) __a = tf.keras.Model(A_ , A_ ) keras_model.save(A_ ) def UpperCamelCase__ ( self ) -> Union[str, Any]: # Has PT equivalent: this test relies on random sampling __a = { 'do_sample': True, 'num_beams': 1, 'top_p': 0.7, 'top_k': 10, 'temperature': 0.7, } __a = 14 __a = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __a = 'Hello, my dog is cute and' __a = tokenizer(A_ , return_tensors='tf' ) __a = TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __a = 638 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(':/CPU:0' ): tf.random.set_seed(0 ) __a = model.generate(**A_ , eos_token_id=A_ , **A_ ) self.assertTrue(expectation == len(generated_tokens[0] ) ) __a = [638, 198] with tf.device(':/CPU:0' ): tf.random.set_seed(0 ) __a = model.generate(**A_ , eos_token_id=A_ , **A_ ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def UpperCamelCase__ ( self ) -> List[Any]: # Has PT equivalent: ample use of framework-specific code __a = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-bart' ) __a = 'Hugging Face is a technology company based in New York and Paris.' __a = bart_tokenizer(A_ , return_tensors='tf' ).input_ids __a = TFBartForConditionalGeneration.from_pretrained('hf-internal-testing/tiny-random-bart' ) __a = bart_model.generate(A_ ).numpy() class __lowercase ( _lowercase ): def UpperCamelCase__ ( self , UpperCamelCase , UpperCamelCase=None , **UpperCamelCase ) -> Dict: return super().call(A_ , **A_ ) __a = FakeBart.from_pretrained('hf-internal-testing/tiny-random-bart' ) __a = bart_model.generate(A_ , foo='bar' ).numpy() self.assertTrue(np.array_equal(A_ , A_ ) ) class __lowercase ( bart_model.model.encoder.__class__ ): def UpperCamelCase__ ( self , UpperCamelCase , **UpperCamelCase ) -> str: return super().call(A_ , **A_ ) __a = FakeEncoder(bart_model.config , bart_model.model.shared ) __a = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) __a = bart_model.generate(A_ ).numpy() with self.assertRaises(A_ ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(A_ , foo='bar' )
539
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers _lowercase = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def _snake_case ( ): A = os.path.dirname(os.path.realpath(snake_case__ ) ) A = os.path.join(snake_case__ , 'words.txt' ) A = '' with open(snake_case__ ) as f: A = f.readline() A = [word.strip('"' ) for word in words.strip('\r\n' ).split(',' )] A = [ word for word in [sum(ord(snake_case__ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(snake_case__ ) if __name__ == "__main__": print(solution())
91
0
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 , _lowerCamelCase , _lowerCamelCase=1_2 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=5_1_2 , _lowerCamelCase=0.0_2 , _lowerCamelCase=0 , _lowerCamelCase=None , ): UpperCamelCase_: Any = parent UpperCamelCase_: int = batch_size UpperCamelCase_: Any = seq_length UpperCamelCase_: Any = is_training UpperCamelCase_: Any = use_input_mask UpperCamelCase_: Union[str, Any] = use_labels UpperCamelCase_: Optional[int] = vocab_size UpperCamelCase_: Dict = hidden_size UpperCamelCase_: Optional[int] = projection_dim UpperCamelCase_: Dict = num_hidden_layers UpperCamelCase_: str = num_attention_heads UpperCamelCase_: Optional[int] = intermediate_size UpperCamelCase_: List[Any] = dropout UpperCamelCase_: Dict = attention_dropout UpperCamelCase_: Optional[int] = max_position_embeddings UpperCamelCase_: Union[str, Any] = initializer_range UpperCamelCase_: List[str] = scope UpperCamelCase_: Dict = bos_token_id def _a ( self ): UpperCamelCase_: Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_: Optional[int] = None if self.use_input_mask: UpperCamelCase_: int = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: UpperCamelCase_: List[Any] = input_mask.numpy() UpperCamelCase_ ,UpperCamelCase_: List[Any] = input_mask.shape UpperCamelCase_: Optional[int] = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(A_ ): UpperCamelCase_: List[str] = 1 UpperCamelCase_: Any = 0 UpperCamelCase_: Optional[int] = self.get_config() return config, input_ids, tf.convert_to_tensor(A_ ) def _a ( self ): 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 _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = TFBlipTextModel(config=A_ ) UpperCamelCase_: Dict = model(A_ , attention_mask=A_ , training=A_ ) UpperCamelCase_: Union[str, Any] = model(A_ , training=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _a ( self ): UpperCamelCase_: List[str] = self.prepare_config_and_inputs() UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = config_and_inputs UpperCamelCase_: Any = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class _lowerCAmelCase( _lowercase , unittest.TestCase ): """simple docstring""" a : List[str] =(TFBlipTextModel,) if is_tf_available() else () a : Optional[int] =False a : str =False a : Optional[int] =False def _a ( self ): UpperCamelCase_: int = BlipTextModelTester(self ) UpperCamelCase_: Optional[int] = ConfigTester(self , config_class=A_ , hidden_size=3_7 ) def _a ( self ): self.config_tester.run_common_tests() def _a ( self ): UpperCamelCase_: Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _a ( self ): pass def _a ( self ): pass @unittest.skip(reason='Blip does not use inputs_embeds' ) def _a ( self ): pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def _a ( self ): pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def _a ( self ): pass @slow def _a ( self ): for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase_: Any = TFBlipTextModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _a ( self , _lowerCamelCase=True ): super().test_pt_tf_model_equivalence(allow_missing_keys=A_ )
57
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''', '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''mobilenet_v1''' def __init__( self : Optional[int] ,A_ : Optional[int]=3 ,A_ : Any=224 ,A_ : List[Any]=1.0 ,A_ : Union[str, Any]=8 ,A_ : Union[str, Any]="relu6" ,A_ : Optional[Any]=True ,A_ : List[str]=0.9_99 ,A_ : int=0.02 ,A_ : int=0.0_01 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) A = num_channels A = image_size A = depth_multiplier A = min_depth A = hidden_act A = tf_padding A = classifier_dropout_prob A = initializer_range A = layer_norm_eps class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> float: return 1e-4
91
0
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def __UpperCamelCase ( ): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(snake_case__ ): requests.request('''GET''' , '''https://huggingface.co''' ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request('''GET''' , '''https://huggingface.co''' , timeout=1.0 ) @pytest.mark.integration def __UpperCamelCase ( ): with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request('''GET''' , '''https://huggingface.co''' ) def __UpperCamelCase ( ): with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(snake_case__ ): http_head('''https://huggingface.co''' )
521
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ElectraForCausalLM''', '''ElectraForMaskedLM''', '''ElectraForMultipleChoice''', '''ElectraForPreTraining''', '''ElectraForQuestionAnswering''', '''ElectraForSequenceClassification''', '''ElectraForTokenClassification''', '''ElectraModel''', '''ElectraPreTrainedModel''', '''load_tf_weights_in_electra''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFElectraForMaskedLM''', '''TFElectraForMultipleChoice''', '''TFElectraForPreTraining''', '''TFElectraForQuestionAnswering''', '''TFElectraForSequenceClassification''', '''TFElectraForTokenClassification''', '''TFElectraModel''', '''TFElectraPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxElectraForCausalLM''', '''FlaxElectraForMaskedLM''', '''FlaxElectraForMultipleChoice''', '''FlaxElectraForPreTraining''', '''FlaxElectraForQuestionAnswering''', '''FlaxElectraForSequenceClassification''', '''FlaxElectraForTokenClassification''', '''FlaxElectraModel''', '''FlaxElectraPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
from math import pow def _a ( a :int , a :int , a :int , a :int , a :int , ) -> Dict: 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 a = int(pow(snake_case__ , snake_case__ ) ) 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 a , a = backtrack( snake_case__ , snake_case__ , current_number + 1 , snake_case__ , snake_case__ ) 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. a , a = backtrack( snake_case__ , snake_case__ , current_number + 1 , snake_case__ , snake_case__ ) return current_sum, solutions_count def _a ( a :int , a :int ) -> Optional[int]: if not (1 <= needed_sum <= 1_000 and 2 <= power <= 10): raise ValueError( '''Invalid input\n''' '''needed_sum must be between 1 and 1000, power between 2 and 10.''' ) return backtrack(snake_case__ , snake_case__ , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
117
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal _lowercase = datasets.utils.logging.get_logger(__name__) _lowercase = ['''names''', '''prefix'''] _lowercase = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] _lowercase = ['''encoding_errors''', '''on_bad_lines'''] _lowercase = ['''date_format'''] @dataclass class lowerCAmelCase_ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCamelCase: str = "," _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[int, List[int], str]] = "infer" _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[List[str]] = None _lowerCamelCase: Optional[Union[int, str, List[int], List[str]]] = None _lowerCamelCase: Optional[Union[List[int], List[str]]] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: Optional[Literal["c", "python", "pyarrow"]] = None _lowerCamelCase: Dict[Union[int, str], Callable[[Any], Any]] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: Optional[list] = None _lowerCamelCase: bool = False _lowerCamelCase: Optional[Union[int, List[int]]] = None _lowerCamelCase: Optional[int] = None _lowerCamelCase: Optional[Union[str, List[str]]] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: bool = True _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = "." _lowerCamelCase: Optional[str] = None _lowerCamelCase: str = '"' _lowerCamelCase: int = 0 _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[str] = None _lowerCamelCase: bool = True _lowerCamelCase: bool = True _lowerCamelCase: int = 0 _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: Optional[str] = None _lowerCamelCase: int = 10000 _lowerCamelCase: Optional[datasets.Features] = None _lowerCamelCase: Optional[str] = "strict" _lowerCamelCase: Literal["error", "warn", "skip"] = "error" _lowerCamelCase: Optional[str] = None def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: if self.delimiter is not None: A = self.delimiter if self.column_names is not None: A = self.column_names @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() ,A_ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class lowerCAmelCase_ ( datasets.ArrowBasedBuilder ): '''simple docstring''' _lowerCamelCase: Any = CsvConfig def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return datasets.DatasetInfo(features=self.config.features ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Any ) -> str: if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A_ ,(str, list, tuple) ): A = data_files if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,gen_kwargs={'files': files} )] A = [] for split_name, files in data_files.items(): if isinstance(A_ ,A_ ): A = [files] A = [dl_manager.iter_files(A_ ) for file in files] splits.append(datasets.SplitGenerator(name=A_ ,gen_kwargs={'files': files} ) ) return splits def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : pa.Table ) -> pa.Table: if self.config.features is not None: A = self.config.features.arrow_schema if all(not require_storage_cast(A_ ) for feature in self.config.features.values() ): # cheaper cast A = pa.Table.from_arrays([pa_table[field.name] for field in schema] ,schema=A_ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A = table_cast(A_ ,A_ ) return pa_table def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ) -> List[Any]: A = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(A_ ) else object for name, dtype, feature in zip(schema.names ,schema.types ,self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(A_ ) ): A = pd.read_csv(A_ ,iterator=A_ ,dtype=A_ ,**self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(A_ ): A = pa.Table.from_pandas(A_ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(A_ ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(A_ )}: {e}' ) raise
91
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: _UpperCAmelCase : Tuple = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=A_ ).to(A_ ) _UpperCAmelCase : str = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _UpperCAmelCase : Optional[int] = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids _UpperCAmelCase : List[str] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids _UpperCAmelCase : Union[str, Any] = model(input_ids.to(A_ ) , labels=labels.to(A_ ) ).loss _UpperCAmelCase : Any = -(labels.shape[-1] * loss.item()) _UpperCAmelCase : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
506
"""simple docstring""" from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Any ,A_ : Callable ,A_ : Optional[Features] = None ,A_ : str = None ,A_ : bool = False ,A_ : bool = False ,A_ : Optional[dict] = None ,A_ : Optional[int] = None ,**A_ : int ,) -> str: super().__init__( features=A_ ,cache_dir=A_ ,keep_in_memory=A_ ,streaming=A_ ,num_proc=A_ ,**A_ ,) A = Generator( cache_dir=A_ ,features=A_ ,generator=A_ ,gen_kwargs=A_ ,**A_ ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: # Build iterable dataset if self.streaming: A = self.builder.as_streaming_dataset(split='train' ) # Build regular (map-style) dataset else: A = None A = None A = None A = None self.builder.download_and_prepare( download_config=A_ ,download_mode=A_ ,verification_mode=A_ ,base_path=A_ ,num_proc=self.num_proc ,) A = self.builder.as_dataset( split='train' ,verification_mode=A_ ,in_memory=self.keep_in_memory ) return dataset
91
0
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class a_ ( unittest.TestCase ): a : Dict = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def UpperCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): _lowercase = hf_hub_download( repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) _lowercase = VideoClassificationPipeline(model=A_ , image_processor=A_ , top_k=2 ) _lowercase = [ example_video_filepath, """https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4""", ] return video_classifier, examples def UpperCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase ): for example in examples: _lowercase = video_classifier(A_ ) self.assertEqual( A_ , [ {"""score""": ANY(A_ ), """label""": ANY(A_ )}, {"""score""": ANY(A_ ), """label""": ANY(A_ )}, ] , ) @require_torch def UpperCamelCase_ ( self ): _lowercase = """hf-internal-testing/tiny-random-VideoMAEForVideoClassification""" _lowercase = VideoMAEFeatureExtractor( size={"""shortest_edge""": 10} , crop_size={"""height""": 10, """width""": 10} ) _lowercase = pipeline( """video-classification""" , model=A_ , feature_extractor=A_ , frame_sampling_rate=4 ) _lowercase = hf_hub_download(repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) _lowercase = video_classifier(A_ , top_k=2 ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [{"""score""": 0.51_99, """label""": """LABEL_0"""}, {"""score""": 0.48_01, """label""": """LABEL_1"""}] , ) _lowercase = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ [{"""score""": 0.51_99, """label""": """LABEL_0"""}, {"""score""": 0.48_01, """label""": """LABEL_1"""}], [{"""score""": 0.51_99, """label""": """LABEL_0"""}, {"""score""": 0.48_01, """label""": """LABEL_1"""}], ] , ) @require_tf def UpperCamelCase_ ( self ): pass
287
"""simple docstring""" from maths.prime_check import is_prime def _snake_case ( snake_case__ : int ): if not isinstance(snake_case__ , snake_case__ ): A = F'Input value of [number={number}] must be an integer' raise TypeError(snake_case__ ) if is_prime(snake_case__ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
91
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Any class __snake_case: '''simple docstring''' def __init__( self , A_ ) -> List[Any]: lowerCAmelCase = data lowerCAmelCase = None class __snake_case: '''simple docstring''' def __init__( self ) -> List[str]: lowerCAmelCase = None lowerCAmelCase = None def __iter__( self ) -> Iterator[Any]: lowerCAmelCase = self.head while self.head: yield node.data lowerCAmelCase = node.next if node == self.head: break def __len__( self ) -> int: return sum(1 for _ in self ) def __repr__( self ) -> Union[str, Any]: return "->".join(str(A_ ) for item in iter(self ) ) def __snake_case ( self , A_ ) -> None: self.insert_nth(len(self ) , A_ ) def __snake_case ( self , A_ ) -> None: self.insert_nth(0 , A_ ) def __snake_case ( self , A_ , A_ ) -> None: if index < 0 or index > len(self ): raise IndexError("""list index out of range.""" ) lowerCAmelCase = Node(A_ ) if self.head is None: lowerCAmelCase = new_node # first node points itself lowerCAmelCase = lowerCAmelCase = new_node elif index == 0: # insert at head lowerCAmelCase = self.head lowerCAmelCase = lowerCAmelCase = new_node else: lowerCAmelCase = self.head for _ in range(index - 1 ): lowerCAmelCase = temp.next lowerCAmelCase = temp.next lowerCAmelCase = new_node if index == len(self ) - 1: # insert at tail lowerCAmelCase = new_node def __snake_case ( self ) -> Union[str, Any]: return self.delete_nth(0 ) def __snake_case ( self ) -> Any: return self.delete_nth(len(self ) - 1 ) def __snake_case ( self , A_ = 0 ) -> Any: if not 0 <= index < len(self ): raise IndexError("""list index out of range.""" ) lowerCAmelCase = self.head if self.head == self.tail: # just one node lowerCAmelCase = lowerCAmelCase = None elif index == 0: # delete head node lowerCAmelCase = self.tail.next.next lowerCAmelCase = self.head.next else: lowerCAmelCase = self.head for _ in range(index - 1 ): lowerCAmelCase = temp.next lowerCAmelCase = temp.next lowerCAmelCase = temp.next.next if index == len(self ) - 1: # delete at tail lowerCAmelCase = temp return delete_node.data def __snake_case ( self ) -> bool: return len(self ) == 0 def _snake_case ( ) -> List[str]: """simple docstring""" lowerCAmelCase = CircularLinkedList() assert len(snake_case__ ) == 0 assert circular_linked_list.is_empty() is True assert str(snake_case__ ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(snake_case__ ) == i circular_linked_list.insert_nth(snake_case__ , i + 1 ) assert str(snake_case__ ) == "->".join(str(snake_case__ ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(snake_case__ ) == "->".join(str(snake_case__ ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(snake_case__ ) == "->".join(str(snake_case__ ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(snake_case__ ) == "->".join(str(snake_case__ ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(snake_case__ ) == "->".join(str(snake_case__ ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
433
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[str]=0 ) -> str: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = OnnxStableDiffusionImgaImgPipeline.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_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) 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_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = OnnxStableDiffusionImgaImgPipeline.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_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: A = OnnxStableDiffusionImgaImgPipeline.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.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.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 ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
91
0
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool lowerCAmelCase__ = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class lowerCAmelCase__ ( _lowercase): '''simple docstring''' __SCREAMING_SNAKE_CASE = '''facebook/nllb-200-distilled-600M''' __SCREAMING_SNAKE_CASE = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) __SCREAMING_SNAKE_CASE = '''translator''' __SCREAMING_SNAKE_CASE = AutoTokenizer __SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM __SCREAMING_SNAKE_CASE = LANGUAGE_CODES __SCREAMING_SNAKE_CASE = ['''text''', '''text''', '''text'''] __SCREAMING_SNAKE_CASE = ['''text'''] def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> Tuple: if src_lang not in self.lang_to_code: raise ValueError(F"{src_lang} is not a supported language.") if tgt_lang not in self.lang_to_code: raise ValueError(F"{tgt_lang} is not a supported language.") _A : Any = self.lang_to_code[src_lang] _A : Dict = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( A_ , return_tensors="pt" , src_lang=A_ , tgt_lang=A_) def _lowerCamelCase ( self , __lowerCamelCase) -> int: return self.model.generate(**A_) def _lowerCamelCase ( self , __lowerCamelCase) -> List[Any]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=A_)
503
"""simple docstring""" from __future__ import annotations def _snake_case ( snake_case__ : tuple[int, int] , snake_case__ : int ): A , A = position A = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] A = [] for position in positions: A , A = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(snake_case__ ) return permissible_positions def _snake_case ( snake_case__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _snake_case ( snake_case__ : list[list[int]] , snake_case__ : tuple[int, int] , snake_case__ : int ): if is_complete(snake_case__ ): return True for position in get_valid_pos(snake_case__ , len(snake_case__ ) ): A , A = position if board[y][x] == 0: A = curr + 1 if open_knight_tour_helper(snake_case__ , snake_case__ , curr + 1 ): return True A = 0 return False def _snake_case ( snake_case__ : int ): A = [[0 for i in range(snake_case__ )] for j in range(snake_case__ )] for i in range(snake_case__ ): for j in range(snake_case__ ): A = 1 if open_knight_tour_helper(snake_case__ , (i, j) , 1 ): return board A = 0 A = F'Open Kight Tour cannot be performed on a board of size {n}' raise ValueError(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod()
91
0
"""simple docstring""" class __lowerCAmelCase : '''simple docstring''' def __init__( self ): __a = '''''' __a = '''''' __a = [] def __UpperCAmelCase ( self , _a , _a ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: __a = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: __a = self.__min_dist_top_down_dp(A_ , n - 1 ) __a = self.__min_dist_top_down_dp(m - 1 , A_ ) __a = self.__min_dist_top_down_dp(m - 1 , n - 1 ) __a = 1 + min(A_ , A_ , A_ ) return self.dp[m][n] def __UpperCAmelCase ( self , _a , _a ): __a = worda __a = worda __a = [[-1 for _ in range(len(A_ ) )] for _ in range(len(A_ ) )] return self.__min_dist_top_down_dp(len(A_ ) - 1 , len(A_ ) - 1 ) def __UpperCAmelCase ( self , _a , _a ): __a = worda __a = worda __a = len(A_ ) __a = len(A_ ) __a = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty __a = j elif j == 0: # second string is empty __a = i elif worda[i - 1] == worda[j - 1]: # last characters are equal __a = self.dp[i - 1][j - 1] else: __a = self.dp[i][j - 1] __a = self.dp[i - 1][j] __a = self.dp[i - 1][j - 1] __a = 1 + min(A_ , A_ , A_ ) return self.dp[m][n] if __name__ == "__main__": lowercase_ = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() lowercase_ = input("Enter the first string: ").strip() lowercase_ = input("Enter the second string: ").strip() print() print(F'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(F'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
695
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Optional[int] = BlenderbotSmallTokenizer _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: super().setUp() A = ['__start__', 'adapt', 'act', 'ap@@', 'te', '__end__', '__unk__'] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['#version: 0.2', 'a p', 't e</w>', 'ap t</w>', 'a d', 'ad apt</w>', 'a c', 'ac t</w>', ''] A = {'unk_token': '__unk__', 'bos_token': '__start__', 'eos_token': '__end__'} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,**A_ : Union[str, Any] ) -> Optional[int]: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Tuple ) -> List[Any]: A = 'adapt act apte' A = 'adapt act apte' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: A = BlenderbotSmallTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) A = 'adapt act apte' A = ['adapt', 'act', 'ap@@', 'te'] A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] A = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) assert tok('sam' ).input_ids == [1384] A = 'I am a small frog.' A = tok([src_text] ,padding=A_ ,truncation=A_ )['input_ids'] A = tok.batch_decode(A_ ,skip_special_tokens=A_ ,clean_up_tokenization_spaces=A_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) A = 'I am a small frog .' A = '.' A = tok(A_ )['input_ids'] A = tok(A_ )['input_ids'] assert encoded[-1] == encoded_dot[0]
91
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { "google/bit-50": "https://huggingface.co/google/bit-50/resolve/main/config.json", } class lowerCAmelCase_ ( _lowercase , _lowercase ): """simple docstring""" _snake_case : Any = '''bit''' _snake_case : List[Any] = ['''preactivation''', '''bottleneck'''] _snake_case : Tuple = ['''SAME''', '''VALID'''] def __init__( self :Union[str, Any] , lowerCamelCase__ :Tuple=3 , lowerCamelCase__ :List[Any]=64 , lowerCamelCase__ :Optional[int]=[2_56, 5_12, 10_24, 20_48] , lowerCamelCase__ :List[Any]=[3, 4, 6, 3] , lowerCamelCase__ :Optional[Any]="preactivation" , lowerCamelCase__ :Optional[int]="relu" , lowerCamelCase__ :Optional[Any]=None , lowerCamelCase__ :Any=32 , lowerCamelCase__ :Union[str, Any]=0.0 , lowerCamelCase__ :Optional[int]=False , lowerCamelCase__ :Tuple=32 , lowerCamelCase__ :Dict=1 , lowerCamelCase__ :str=None , lowerCamelCase__ :List[str]=None , **lowerCamelCase__ :Dict , ): super().__init__(**A_ ) if layer_type not in self.layer_types: raise ValueError(f"""layer_type={layer_type} is not one of {",".join(self.layer_types )}""" ) if global_padding is not None: if global_padding.upper() in self.supported_padding: UpperCamelCase__ :str = global_padding.upper() else: raise ValueError(f"""Padding strategy {global_padding} not supported""" ) UpperCamelCase__ :Tuple = num_channels UpperCamelCase__ :List[Any] = embedding_size UpperCamelCase__ :List[Any] = hidden_sizes UpperCamelCase__ :Tuple = depths UpperCamelCase__ :List[Any] = layer_type UpperCamelCase__ :str = hidden_act UpperCamelCase__ :Optional[int] = global_padding UpperCamelCase__ :Union[str, Any] = num_groups UpperCamelCase__ :Optional[int] = drop_path_rate UpperCamelCase__ :List[Any] = embedding_dynamic_padding UpperCamelCase__ :Union[str, Any] = output_stride UpperCamelCase__ :Dict = width_factor UpperCamelCase__ :str = ["""stem"""] + [f"""stage{idx}""" for idx in range(1 , len(A_ ) + 1 )] UpperCamelCase__ , UpperCamelCase__ :Dict = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names )
45
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''image_processor''', '''tokenizer'''] _lowerCamelCase: Optional[int] = '''Pix2StructImageProcessor''' _lowerCamelCase: Dict = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : Optional[int] ,A_ : List[str] ,A_ : Optional[int] ) -> int: A = False super().__init__(A_ ,A_ ) def __call__( self : Any ,A_ : List[str]=None ,A_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,A_ : bool = True ,A_ : Union[bool, str, PaddingStrategy] = False ,A_ : Union[bool, str, TruncationStrategy] = None ,A_ : Optional[int] = None ,A_ : Optional[int] = 2048 ,A_ : int = 0 ,A_ : Optional[int] = None ,A_ : Optional[bool] = None ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = True ,A_ : Optional[Union[str, TensorType]] = None ,**A_ : Tuple ,) -> BatchEncoding: if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None and not self.image_processor.is_vqa: A = self.tokenizer A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,**A_ ) else: # add pixel_values and bbox A = self.image_processor( A_ ,return_tensors=A_ ,max_patches=A_ ,header_text=A_ ,**A_ ) if text is not None and not self.image_processor.is_vqa: A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) if "attention_mask" in text_encoding: A = text_encoding.pop('attention_mask' ) if "input_ids" in text_encoding: A = text_encoding.pop('input_ids' ) else: A = None if text_encoding is not None: encoding_image_processor.update(A_ ) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,*A_ : Optional[Any] ,**A_ : Dict ) -> Union[str, Any]: return self.tokenizer.batch_decode(*A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,*A_ : Tuple ,**A_ : List[str] ) -> Any: return self.tokenizer.decode(*A_ ,**A_ ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: A = self.tokenizer.model_input_names A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
91
0
"""simple docstring""" import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowercase_ ( ) -> str: '''simple docstring''' __lowerCamelCase : List[str] = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png" __lowerCamelCase : int = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ).convert("RGB" ) return image def lowercase_ ( _lowerCamelCase: Dict ) -> List[str]: '''simple docstring''' __lowerCamelCase : int = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F"""visual_encoder.blocks.{i}.norm1.weight""", F"""vision_model.encoder.layers.{i}.layer_norm1.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.norm1.bias""", F"""vision_model.encoder.layers.{i}.layer_norm1.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.norm2.weight""", F"""vision_model.encoder.layers.{i}.layer_norm2.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.norm2.bias""", F"""vision_model.encoder.layers.{i}.layer_norm2.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.attn.qkv.weight""", F"""vision_model.encoder.layers.{i}.self_attn.qkv.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.attn.proj.weight""", F"""vision_model.encoder.layers.{i}.self_attn.projection.weight""",) ) rename_keys.append((F"""visual_encoder.blocks.{i}.attn.proj.bias""", F"""vision_model.encoder.layers.{i}.self_attn.projection.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc1.weight""", F"""vision_model.encoder.layers.{i}.mlp.fc1.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc1.bias""", F"""vision_model.encoder.layers.{i}.mlp.fc1.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc2.weight""", F"""vision_model.encoder.layers.{i}.mlp.fc2.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc2.bias""", F"""vision_model.encoder.layers.{i}.mlp.fc2.bias""") ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.layernorm.bias") ) # fmt: on return rename_keys def lowercase_ ( _lowerCamelCase: Dict , _lowerCamelCase: int , _lowerCamelCase: str ) -> Tuple: '''simple docstring''' __lowerCamelCase : Union[str, Any] = dct.pop(snake_case__ ) __lowerCamelCase : Any = val def lowercase_ ( _lowerCamelCase: Optional[int] , _lowerCamelCase: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __lowerCamelCase : Union[str, Any] = state_dict.pop(F"""visual_encoder.blocks.{i}.attn.q_bias""" ) __lowerCamelCase : List[str] = state_dict.pop(F"""visual_encoder.blocks.{i}.attn.v_bias""" ) # next, set bias in the state dict __lowerCamelCase : Optional[int] = torch.cat((q_bias, torch.zeros_like(snake_case__ , requires_grad=snake_case__ ), v_bias) ) __lowerCamelCase : Tuple = qkv_bias def lowercase_ ( _lowerCamelCase: Optional[int] , _lowerCamelCase: int ) -> Tuple: '''simple docstring''' __lowerCamelCase : str = 364 if "coco" in model_name else 224 __lowerCamelCase : int = BlipaVisionConfig(image_size=snake_case__ ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: __lowerCamelCase : int = OPTConfig.from_pretrained("facebook/opt-2.7b" , eos_token_id=snake_case__ ).to_dict() elif "opt-6.7b" in model_name: __lowerCamelCase : List[str] = OPTConfig.from_pretrained("facebook/opt-6.7b" , eos_token_id=snake_case__ ).to_dict() elif "t5-xl" in model_name: __lowerCamelCase : int = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __lowerCamelCase : Any = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() __lowerCamelCase : Dict = BlipaConfig(vision_config=snake_case__ , text_config=snake_case__ ) return config, image_size @torch.no_grad() def lowercase_ ( _lowerCamelCase: Optional[Any] , _lowerCamelCase: List[Any]=None , _lowerCamelCase: List[Any]=False ) -> str: '''simple docstring''' __lowerCamelCase : List[Any] = ( AutoTokenizer.from_pretrained("facebook/opt-2.7b" ) if "opt" in model_name else AutoTokenizer.from_pretrained("google/flan-t5-xl" ) ) __lowerCamelCase : str = tokenizer("\n" , add_special_tokens=snake_case__ ).input_ids[0] __lowerCamelCase , __lowerCamelCase : Optional[int] = get_blipa_config(snake_case__ , eos_token_id=snake_case__ ) __lowerCamelCase : List[Any] = BlipaForConditionalGeneration(snake_case__ ).eval() __lowerCamelCase : str = { "blip2-opt-2.7b": ("blip2_opt", "pretrain_opt2.7b"), "blip2-opt-6.7b": ("blip2_opt", "pretrain_opt6.7b"), "blip2-opt-2.7b-coco": ("blip2_opt", "caption_coco_opt2.7b"), "blip2-opt-6.7b-coco": ("blip2_opt", "caption_coco_opt6.7b"), "blip2-flan-t5-xl": ("blip2_t5", "pretrain_flant5xl"), "blip2-flan-t5-xl-coco": ("blip2_t5", "caption_coco_flant5xl"), "blip2-flan-t5-xxl": ("blip2_t5", "pretrain_flant5xxl"), } __lowerCamelCase , __lowerCamelCase : List[str] = model_name_to_original[model_name] # load original model print("Loading original model..." ) __lowerCamelCase : List[Any] = "cuda" if torch.cuda.is_available() else "cpu" __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = load_model_and_preprocess( name=snake_case__ , model_type=snake_case__ , is_eval=snake_case__ , device=snake_case__ ) original_model.eval() print("Done!" ) # update state dict keys __lowerCamelCase : Any = original_model.state_dict() __lowerCamelCase : List[str] = create_rename_keys(snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __lowerCamelCase : int = state_dict.pop(snake_case__ ) if key.startswith("Qformer.bert" ): __lowerCamelCase : Any = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: __lowerCamelCase : Any = key.replace("self" , "attention" ) if "opt_proj" in key: __lowerCamelCase : Any = key.replace("opt_proj" , "language_projection" ) if "t5_proj" in key: __lowerCamelCase : Any = key.replace("t5_proj" , "language_projection" ) if key.startswith("opt" ): __lowerCamelCase : Any = key.replace("opt" , "language" ) if key.startswith("t5" ): __lowerCamelCase : str = key.replace("t5" , "language" ) __lowerCamelCase : int = val # read in qv biases read_in_q_v_bias(snake_case__ , snake_case__ ) __lowerCamelCase , __lowerCamelCase : int = hf_model.load_state_dict(snake_case__ , strict=snake_case__ ) assert len(snake_case__ ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] __lowerCamelCase : Optional[Any] = load_demo_image() __lowerCamelCase : int = vis_processors["eval"](snake_case__ ).unsqueeze(0 ).to(snake_case__ ) __lowerCamelCase : str = tokenizer(["\n"] , return_tensors="pt" ).input_ids.to(snake_case__ ) # create processor __lowerCamelCase : List[Any] = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=snake_case__ , image_std=snake_case__ ) __lowerCamelCase : str = BlipaProcessor(image_processor=snake_case__ , tokenizer=snake_case__ ) __lowerCamelCase : str = processor(images=snake_case__ , return_tensors="pt" ).pixel_values.to(snake_case__ ) # make sure processor creates exact same pixel values assert torch.allclose(snake_case__ , snake_case__ ) original_model.to(snake_case__ ) hf_model.to(snake_case__ ) with torch.no_grad(): if "opt" in model_name: __lowerCamelCase : Dict = original_model({"image": original_pixel_values, "text_input": [""]} ).logits __lowerCamelCase : List[Any] = hf_model(snake_case__ , snake_case__ ).logits else: __lowerCamelCase : Tuple = original_model( {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]} ).logits __lowerCamelCase : int = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) __lowerCamelCase : List[str] = hf_model(snake_case__ , snake_case__ , labels=snake_case__ ).logits assert original_logits.shape == logits.shape print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": __lowerCamelCase : int = torch.tensor( [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=snake_case__ ) assert torch.allclose(logits[0, :3, :3] , snake_case__ , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": __lowerCamelCase : List[str] = torch.tensor( [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=snake_case__ ) else: # cast to same type __lowerCamelCase : Dict = logits.dtype assert torch.allclose(original_logits.to(snake_case__ ) , snake_case__ , atol=1E-2 ) print("Looks ok!" ) print("Generating a caption..." ) __lowerCamelCase : Dict = "" __lowerCamelCase : List[str] = tokenizer(snake_case__ , return_tensors="pt" ).input_ids.to(snake_case__ ) __lowerCamelCase : Union[str, Any] = original_model.generate({"image": original_pixel_values} ) __lowerCamelCase : int = hf_model.generate( snake_case__ , snake_case__ , do_sample=snake_case__ , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("Original generation:" , snake_case__ ) __lowerCamelCase : Tuple = input_ids.shape[1] __lowerCamelCase : List[Any] = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=snake_case__ ) __lowerCamelCase : str = [text.strip() for text in output_text] print("HF generation:" , snake_case__ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(snake_case__ ) hf_model.save_pretrained(snake_case__ ) if push_to_hub: processor.push_to_hub(F"""nielsr/{model_name}""" ) hf_model.push_to_hub(F"""nielsr/{model_name}""" ) if __name__ == "__main__": __A = argparse.ArgumentParser() __A = [ '''blip2-opt-2.7b''', '''blip2-opt-6.7b''', '''blip2-opt-2.7b-coco''', '''blip2-opt-6.7b-coco''', '''blip2-flan-t5-xl''', '''blip2-flan-t5-xl-coco''', '''blip2-flan-t5-xxl''', ] parser.add_argument( '''--model_name''', default='''blip2-opt-2.7b''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub after converting''', ) __A = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
646
"""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 _lowercase = logging.get_logger(__name__) _lowercase = '''▁''' _lowercase = {'''vocab_file''': '''sentencepiece.bpe.model'''} _lowercase = { '''vocab_file''': { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model''' ), } } _lowercase = { '''xlm-roberta-base''': 5_12, '''xlm-roberta-large''': 5_12, '''xlm-roberta-large-finetuned-conll02-dutch''': 5_12, '''xlm-roberta-large-finetuned-conll02-spanish''': 5_12, '''xlm-roberta-large-finetuned-conll03-english''': 5_12, '''xlm-roberta-large-finetuned-conll03-german''': 5_12, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[str] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] ,A_ : str ,A_ : str="<s>" ,A_ : Any="</s>" ,A_ : Tuple="</s>" ,A_ : Any="<s>" ,A_ : Optional[Any]="<unk>" ,A_ : int="<pad>" ,A_ : str="<mask>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : Optional[int] ,) -> None: # Mask token behave like a normal word, i.e. include the space before it A = AddedToken(A_ ,lstrip=A_ ,rstrip=A_ ) if isinstance(A_ ,A_ ) else mask_token A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,sep_token=A_ ,cls_token=A_ ,pad_token=A_ ,mask_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) A = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token A = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab A = 1 A = len(self.sp_model ) + self.fairseq_offset A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Union[str, Any] ) -> Any: A = self.__dict__.copy() A = None A = self.sp_model.serialized_model_proto() return state def __setstate__( self : str ,A_ : str ) -> Optional[Any]: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A = [self.cls_token_id] A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[int] ,A_ : Optional[List[int]] = None ) -> List[int]: A = [self.sep_token_id] A = [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 _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[Any] ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] A = self.sp_model.PieceToId(A_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> int: 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 _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = ''.join(A_ ).replace(A_ ,' ' ).strip() return out_string def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
91
0
'''simple docstring''' from math import factorial def SCREAMING_SNAKE_CASE ( a_ : int , a_ : int , a_ : float ): if successes > trials: raise ValueError('successes must be lower or equal to trials' ) if trials < 0 or successes < 0: raise ValueError('the function is defined for non-negative integers' ) if not isinstance(snake_case__ , snake_case__ ) or not isinstance(snake_case__ , snake_case__ ): raise ValueError('the function is defined for non-negative integers' ) if not 0 < prob < 1: raise ValueError('prob has to be in range of 1 - 0' ) __a = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! __a = float(factorial(snake_case__ ) ) coefficient /= factorial(snake_case__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("Probability of 2 successes out of 4 trails") print("with probability of 0.75 is:", end=" ") print(binomial_distribution(2, 4, 0.75))
539
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase_ = {"""tokenization_byt5""": ["""ByT5Tokenizer"""]} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
'''simple docstring''' import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging UpperCamelCase_ = logging.get_logger(__name__) def _lowerCAmelCase ( __magic_name__ : List[str] ) -> Dict: lowercase : List[str] =R'''\w+[.]\d+''' lowercase : List[str] =re.findall(__magic_name__ , __magic_name__ ) for pat in pats: lowercase : Optional[int] =key.replace(__magic_name__ , '''_'''.join(pat.split('''.''' ) ) ) return key def _lowerCAmelCase ( __magic_name__ : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : Dict ) -> str: lowercase : Dict =pt_tuple_key[:-1] + ('''scale''',) if ( any('''norm''' in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): lowercase : str =pt_tuple_key[:-1] + ('''scale''',) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: lowercase : str =pt_tuple_key[:-1] + ('''scale''',) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: lowercase : Dict =pt_tuple_key[:-1] + ('''embedding''',) return renamed_pt_tuple_key, pt_tensor # conv layer lowercase : Tuple =pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: lowercase : Tuple =pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer lowercase : str =pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight": lowercase : Optional[Any] =pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight lowercase : Dict =pt_tuple_key[:-1] + ('''weight''',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias lowercase : Union[str, Any] =pt_tuple_key[:-1] + ('''bias''',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any]=42 ) -> List[str]: # Step 1: Convert pytorch tensor to numpy lowercase : Optional[Any] ={k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params lowercase : str =flax_model.init_weights(PRNGKey(__magic_name__ ) ) lowercase : Dict =flatten_dict(__magic_name__ ) lowercase : Dict ={} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): lowercase : Dict =rename_key(__magic_name__ ) lowercase : Optional[int] =tuple(renamed_pt_key.split('''.''' ) ) # Correctly rename weight parameters lowercase , lowercase : Any =rename_key_and_reshape_tensor(__magic_name__ , __magic_name__ , __magic_name__ ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ''' f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) # also add unexpected weight so that warning is thrown lowercase : Tuple =jnp.asarray(__magic_name__ ) return unflatten_dict(__magic_name__ )
92
1
'''simple docstring''' 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 DetrImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=30 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[int]=1 / 255 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : int=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Any=True , ): '''simple docstring''' # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowercase : Union[str, Any] =size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333} lowercase : List[Any] =parent lowercase : List[str] =batch_size lowercase : Any =num_channels lowercase : Tuple =min_resolution lowercase : Union[str, Any] =max_resolution lowercase : Tuple =do_resize lowercase : Optional[Any] =size lowercase : List[Any] =do_rescale lowercase : Union[str, Any] =rescale_factor lowercase : Dict =do_normalize lowercase : int =image_mean lowercase : Any =image_std lowercase : Union[str, Any] =do_pad def lowerCamelCase_ ( self : Any ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any=False ): '''simple docstring''' if not batched: lowercase : List[Any] =image_inputs[0] if isinstance(UpperCAmelCase__ , Image.Image ): lowercase , lowercase : Dict =image.size else: lowercase , lowercase : Optional[int] =image.shape[1], image.shape[2] if w < h: lowercase : int =int(self.size['''shortest_edge'''] * h / w ) lowercase : Any =self.size['''shortest_edge'''] elif w > h: lowercase : str =self.size['''shortest_edge'''] lowercase : List[str] =int(self.size['''shortest_edge'''] * w / h ) else: lowercase : List[Any] =self.size['''shortest_edge'''] lowercase : List[Any] =self.size['''shortest_edge'''] else: lowercase : List[str] =[] for image in image_inputs: lowercase , lowercase : str =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowercase : List[str] =max(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : item[0] )[0] lowercase : List[str] =max(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( lowercase__ , unittest.TestCase ): lowerCamelCase_ = DetrImageProcessor if is_vision_available() else None def lowerCamelCase_ ( self : str ): '''simple docstring''' lowercase : Any =DetrImageProcessingTester(self ) @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase_ ( self : Dict ): '''simple docstring''' lowercase : Optional[Any] =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_rescale''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''rescale_factor''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_pad''' ) ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : str =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__ ) lowercase : Optional[Any] =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 lowerCamelCase_ ( self : int ): '''simple docstring''' pass def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' # Initialize image_processing lowercase : int =self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input lowercase : Tuple =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values lowercase , lowercase : List[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 lowercase , lowercase : List[str] =self.image_processor_tester.get_expected_values(UpperCAmelCase__ , batched=UpperCAmelCase__ ) lowercase : 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, expected_height, expected_width, ) , ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' # Initialize image_processing lowercase : str =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase : Tuple =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 lowercase : Any =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values lowercase , lowercase : Optional[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 lowercase : List[Any] =image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values lowercase , lowercase : Tuple =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 lowerCamelCase_ ( self : Tuple ): '''simple docstring''' # Initialize image_processing lowercase : int =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase : List[Any] =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 lowercase : Tuple =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values lowercase , lowercase : Optional[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 lowercase : Dict =image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values lowercase , lowercase : Optional[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 lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' # prepare image and target lowercase : Union[str, Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: lowercase : str =json.loads(f.read() ) lowercase : Dict ={'''image_id''': 39769, '''annotations''': target} # encode them lowercase : Union[str, Any] =DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50''' ) lowercase : Optional[int] =image_processing(images=UpperCAmelCase__ , annotations=UpperCAmelCase__ , return_tensors='''pt''' ) # verify pixel values lowercase : int =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , UpperCAmelCase__ ) lowercase : List[str] =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) # verify area lowercase : Any =torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , UpperCAmelCase__ ) ) # verify boxes lowercase : Any =torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , UpperCAmelCase__ ) lowercase : List[str] =torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , UpperCAmelCase__ , atol=1E-3 ) ) # verify image_id lowercase : int =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , UpperCAmelCase__ ) ) # verify is_crowd lowercase : Optional[Any] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , UpperCAmelCase__ ) ) # verify class_labels lowercase : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , UpperCAmelCase__ ) ) # verify orig_size lowercase : Optional[int] =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , UpperCAmelCase__ ) ) # verify size lowercase : Any =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , UpperCAmelCase__ ) ) @slow def lowerCamelCase_ ( self : Dict ): '''simple docstring''' # prepare image, target and masks_path lowercase : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: lowercase : Tuple =json.loads(f.read() ) lowercase : Dict ={'''file_name''': '''000000039769.png''', '''image_id''': 39769, '''segments_info''': target} lowercase : Any =pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them lowercase : Optional[Any] =DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic''' ) lowercase : List[str] =image_processing(images=UpperCAmelCase__ , annotations=UpperCAmelCase__ , masks_path=UpperCAmelCase__ , return_tensors='''pt''' ) # verify pixel values lowercase : Union[str, Any] =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , UpperCAmelCase__ ) lowercase : int =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) # verify area lowercase : Any =torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , UpperCAmelCase__ ) ) # verify boxes lowercase : int =torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , UpperCAmelCase__ ) lowercase : int =torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , UpperCAmelCase__ , atol=1E-3 ) ) # verify image_id lowercase : List[Any] =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , UpperCAmelCase__ ) ) # verify is_crowd lowercase : Optional[int] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , UpperCAmelCase__ ) ) # verify class_labels lowercase : Optional[Any] =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , UpperCAmelCase__ ) ) # verify masks lowercase : str =822873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , UpperCAmelCase__ ) # verify orig_size lowercase : Any =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , UpperCAmelCase__ ) ) # verify size lowercase : str =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , UpperCAmelCase__ ) )
92
'''simple docstring''' from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. UpperCamelCase_ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. UpperCamelCase_ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. UpperCamelCase_ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : str ) -> tuple[str, float]: lowercase : int =len([g for position, g in enumerate(__magic_name__ ) if g == main_target[position]] ) return (item, float(__magic_name__ )) def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : str ) -> tuple[str, str]: lowercase : Any =random.randint(0 , len(__magic_name__ ) - 1 ) lowercase : Tuple =parent_a[:random_slice] + parent_a[random_slice:] lowercase : List[str] =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : list[str] ) -> str: lowercase : Union[str, Any] =list(__magic_name__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: lowercase : Dict =random.choice(__magic_name__ ) return "".join(__magic_name__ ) def _lowerCAmelCase ( __magic_name__ : tuple[str, float] , __magic_name__ : list[tuple[str, float]] , __magic_name__ : list[str] , ) -> list[str]: lowercase : Any =[] # Generate more children proportionally to the fitness score. lowercase : Dict =int(parent_a[1] * 100 ) + 1 lowercase : List[str] =10 if child_n >= 10 else child_n for _ in range(__magic_name__ ): lowercase : List[str] =population_score[random.randint(0 , __magic_name__ )][0] lowercase , lowercase : Dict =crossover(parent_a[0] , __magic_name__ ) # Append new string to the population list. pop.append(mutate(__magic_name__ , __magic_name__ ) ) pop.append(mutate(__magic_name__ , __magic_name__ ) ) return pop def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : list[str] , __magic_name__ : bool = True ) -> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: lowercase : List[str] =f'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(__magic_name__ ) # Verify that the target contains no genes besides the ones inside genes variable. lowercase : Optional[int] =sorted({c for c in target if c not in genes} ) if not_in_genes_list: lowercase : Dict =f'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(__magic_name__ ) # Generate random starting population. lowercase : int =[] for _ in range(__magic_name__ ): population.append(''''''.join([random.choice(__magic_name__ ) for i in range(len(__magic_name__ ) )] ) ) # Just some logs to know what the algorithms is doing. lowercase , lowercase : Optional[int] =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(__magic_name__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. lowercase : List[str] =[evaluate(__magic_name__ , __magic_name__ ) for item in population] # Check if there is a matching evolution. lowercase : int =sorted(__magic_name__ , key=lambda __magic_name__ : x[1] , reverse=__magic_name__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f'''\nGeneration: {generation}''' f'''\nTotal Population:{total_population}''' f'''\nBest score: {population_score[0][1]}''' f'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. lowercase : Any =population[: int(N_POPULATION / 3 )] population.clear() population.extend(__magic_name__ ) # Normalize population score to be between 0 and 1. lowercase : Dict =[ (item, score / len(__magic_name__ )) for item, score in population_score ] # This is selection for i in range(__magic_name__ ): population.extend(select(population_score[int(__magic_name__ )] , __magic_name__ , __magic_name__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(__magic_name__ ) > N_POPULATION: break if __name__ == "__main__": UpperCamelCase_ = ( """This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!""" ) UpperCamelCase_ = list( """ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm""" """nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\""" ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = basic(target_str, genes_list) print( f'''\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}''' )
92
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def _lowerCAmelCase ( __magic_name__ : Union[str, Any]=None ) -> Dict: if subparsers is not None: lowercase : List[Any] =subparsers.add_parser('''test''' ) else: lowercase : Dict =argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' , default=__magic_name__ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=__magic_name__ ) return parser def _lowerCAmelCase ( __magic_name__ : int ) -> Tuple: lowercase : Optional[Any] =os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: lowercase : str =script_name else: lowercase : List[str] =f'''--config_file={args.config_file} {script_name}''' lowercase : str =['''accelerate-launch'''] + test_args.split() lowercase : Optional[int] =execute_subprocess_async(__magic_name__ , env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def _lowerCAmelCase ( ) -> List[Any]: lowercase : Any =test_command_parser() lowercase : Optional[Any] =parser.parse_args() test_command(__magic_name__ ) if __name__ == "__main__": main()
92
'''simple docstring''' import datasets UpperCamelCase_ = """\ @InProceedings{conneau2018xnli, author = \"Conneau, Alexis and Rinott, Ruty and Lample, Guillaume and Williams, Adina and Bowman, Samuel R. and Schwenk, Holger and Stoyanov, Veselin\", title = \"XNLI: Evaluating Cross-lingual Sentence Representations\", booktitle = \"Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing\", year = \"2018\", publisher = \"Association for Computational Linguistics\", location = \"Brussels, Belgium\", } """ UpperCamelCase_ = """\ XNLI is a subset of a few thousand examples from MNLI which has been translated into a 14 different languages (some low-ish resource). As with MNLI, the goal is to predict textual entailment (does sentence A imply/contradict/neither sentence B) and is a classification task (given two sentences, predict one of three labels). """ UpperCamelCase_ = """ Computes XNLI score which is just simple accuracy. Args: predictions: Predicted labels. references: Ground truth labels. Returns: 'accuracy': accuracy Examples: >>> predictions = [0, 1] >>> references = [0, 1] >>> xnli_metric = datasets.load_metric(\"xnli\") >>> results = xnli_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} """ def _lowerCAmelCase ( __magic_name__ : Dict , __magic_name__ : Union[str, Any] ) -> Union[str, Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def lowerCamelCase_ ( self : str ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def lowerCamelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] ): '''simple docstring''' return {"accuracy": simple_accuracy(UpperCAmelCase__ , UpperCAmelCase__ )}
92
1
'''simple docstring''' import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() UpperCamelCase_ = logging.get_logger("""transformers.models.speecht5""") UpperCamelCase_ = { """speech_encoder_prenet.layer_norm""": """speecht5.encoder.prenet.feature_projection.layer_norm""", """speech_encoder_prenet.post_extract_proj""": """speecht5.encoder.prenet.feature_projection.projection""", """speech_encoder_prenet.pos_conv.0""": """speecht5.encoder.prenet.pos_conv_embed.conv""", """speech_encoder_prenet.mask_emb""": """speecht5.encoder.prenet.masked_spec_embed""", } UpperCamelCase_ = { """text_encoder_prenet.encoder_prenet.0""": """speecht5.encoder.prenet.embed_tokens""", """text_encoder_prenet.encoder_prenet.1.alpha""": """speecht5.encoder.prenet.encode_positions.alpha""", } UpperCamelCase_ = { """speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0""": """speecht5.decoder.prenet.layers.0""", """speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0""": """speecht5.decoder.prenet.layers.1""", """speech_decoder_prenet.decoder_prenet.0.1""": """speecht5.decoder.prenet.final_layer""", """speech_decoder_prenet.decoder_prenet.1.alpha""": """speecht5.decoder.prenet.encode_positions.alpha""", """speech_decoder_prenet.spkembs_layer.0""": """speecht5.decoder.prenet.speaker_embeds_layer""", } UpperCamelCase_ = { """speech_decoder_postnet.feat_out""": """speech_decoder_postnet.feat_out""", """speech_decoder_postnet.prob_out""": """speech_decoder_postnet.prob_out""", """speech_decoder_postnet.postnet.postnet.0.0""": """speech_decoder_postnet.layers.0.conv""", """speech_decoder_postnet.postnet.postnet.0.1""": """speech_decoder_postnet.layers.0.batch_norm""", """speech_decoder_postnet.postnet.postnet.1.0""": """speech_decoder_postnet.layers.1.conv""", """speech_decoder_postnet.postnet.postnet.1.1""": """speech_decoder_postnet.layers.1.batch_norm""", """speech_decoder_postnet.postnet.postnet.2.0""": """speech_decoder_postnet.layers.2.conv""", """speech_decoder_postnet.postnet.postnet.2.1""": """speech_decoder_postnet.layers.2.batch_norm""", """speech_decoder_postnet.postnet.postnet.3.0""": """speech_decoder_postnet.layers.3.conv""", """speech_decoder_postnet.postnet.postnet.3.1""": """speech_decoder_postnet.layers.3.batch_norm""", """speech_decoder_postnet.postnet.postnet.4.0""": """speech_decoder_postnet.layers.4.conv""", """speech_decoder_postnet.postnet.postnet.4.1""": """speech_decoder_postnet.layers.4.batch_norm""", } UpperCamelCase_ = { """text_decoder_prenet.embed_tokens""": """speecht5.decoder.prenet.embed_tokens""", } UpperCamelCase_ = { """text_decoder_postnet.output_projection""": """text_decoder_postnet.lm_head""", } UpperCamelCase_ = { """encoder.layers.*.self_attn.k_proj""": """speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj""", """encoder.layers.*.self_attn.v_proj""": """speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj""", """encoder.layers.*.self_attn.q_proj""": """speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj""", """encoder.layers.*.self_attn.out_proj""": """speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj""", """encoder.layers.*.self_attn_layer_norm""": """speecht5.encoder.wrapped_encoder.layers.*.layer_norm""", """encoder.layers.*.fc1""": """speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense""", """encoder.layers.*.fc2""": """speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense""", """encoder.layers.*.final_layer_norm""": """speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """speecht5.encoder.wrapped_encoder.layer_norm""", """encoder.pos_emb.pe_k""": """speecht5.encoder.wrapped_encoder.embed_positions.pe_k""", } UpperCamelCase_ = { """decoder.layers.*.self_attn.k_proj""": """speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj""", """decoder.layers.*.self_attn.v_proj""": """speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj""", """decoder.layers.*.self_attn.q_proj""": """speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj""", """decoder.layers.*.self_attn.out_proj""": """speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj""", """decoder.layers.*.self_attn_layer_norm""": """speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm""", """decoder.layers.*.encoder_attn.k_proj""": """speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj""", """decoder.layers.*.encoder_attn.v_proj""": """speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj""", """decoder.layers.*.encoder_attn.q_proj""": """speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj""", """decoder.layers.*.encoder_attn.out_proj""": """speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj""", """decoder.layers.*.encoder_attn_layer_norm""": """speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm""", """decoder.layers.*.fc1""": """speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense""", """decoder.layers.*.fc2""": """speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense""", """decoder.layers.*.final_layer_norm""": """speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm""", } UpperCamelCase_ = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } UpperCamelCase_ = { **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } UpperCamelCase_ = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } UpperCamelCase_ = [] UpperCamelCase_ = [ """encoder.version""", """encoder.layers.*.norm_k.weight""", """encoder.layers.*.norm_k.bias""", """decoder.version""", """decoder.layers.*.norm_k.weight""", """decoder.layers.*.norm_k.bias""", """decoder.pos_emb.pe_k""", """speech_encoder_prenet.embed_positions._float_tensor""", """text_decoder_prenet.embed_positions._float_tensor""", ] UpperCamelCase_ = IGNORE_KEYS + [ """encoder.proj""", """text_encoder_prenet.*""", """speech_decoder_prenet.*""", """speech_decoder_postnet.*""", ] UpperCamelCase_ = IGNORE_KEYS + [ """encoder.proj""", """speech_encoder_prenet.*""", """text_decoder_prenet.*""", """text_decoder_postnet.*""", ] UpperCamelCase_ = IGNORE_KEYS + [ """encoder.proj""", """text_encoder_prenet.*""", """text_decoder_prenet.*""", """text_decoder_postnet.*""", ] def _lowerCAmelCase ( __magic_name__ : List[str] , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : Tuple ) -> List[Any]: for attribute in key.split('''.''' ): lowercase : Any =getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: lowercase : Any =getattr(__magic_name__ , __magic_name__ ).shape else: lowercase : int =hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": lowercase : Optional[Any] =value elif weight_type == "weight_g": lowercase : List[str] =value elif weight_type == "weight_v": lowercase : Any =value elif weight_type == "bias": lowercase : Optional[int] =value elif weight_type == "running_mean": lowercase : List[str] =value elif weight_type == "running_var": lowercase : List[str] =value elif weight_type == "num_batches_tracked": lowercase : int =value else: lowercase : List[Any] =value logger.info(f'''{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.''' ) def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : Optional[Any] ) -> Dict: for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: lowercase , lowercase : int =key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _lowerCAmelCase ( __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : Any ) -> Optional[Any]: lowercase : str =[] if task == "s2t": lowercase : List[Any] =hf_model.speechta.encoder.prenet.feature_encoder lowercase : Optional[int] =MAPPING_S2T lowercase : Optional[Any] =IGNORE_KEYS_S2T elif task == "t2s": lowercase : Optional[Any] =None lowercase : Union[str, Any] =MAPPING_T2S lowercase : List[Any] =IGNORE_KEYS_T2S elif task == "s2s": lowercase : Union[str, Any] =hf_model.speechta.encoder.prenet.feature_encoder lowercase : str =MAPPING_S2S lowercase : List[str] =IGNORE_KEYS_S2S else: raise ValueError(f'''Unsupported task: {task}''' ) for name, value in fairseq_dict.items(): if should_ignore(__magic_name__ , __magic_name__ ): logger.info(f'''{name} was ignored''' ) continue lowercase : str =False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == '''group''' , ) lowercase : Optional[Any] =True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: lowercase , lowercase : Optional[int] =key.split('''.*.''' ) if prefix in name and suffix in name: lowercase : List[str] =suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: lowercase : Dict =True if "*" in mapped_key: lowercase : Optional[Any] =name.split(__magic_name__ )[0].split('''.''' )[-2] lowercase : str =mapped_key.replace('''*''' , __magic_name__ ) if "weight_g" in name: lowercase : int ='''weight_g''' elif "weight_v" in name: lowercase : Tuple ='''weight_v''' elif "bias" in name: lowercase : Tuple ='''bias''' elif "weight" in name: lowercase : Dict ='''weight''' elif "running_mean" in name: lowercase : Any ='''running_mean''' elif "running_var" in name: lowercase : List[str] ='''running_var''' elif "num_batches_tracked" in name: lowercase : str ='''num_batches_tracked''' else: lowercase : Optional[int] =None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _lowerCAmelCase ( __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : List[Any] , __magic_name__ : Dict ) -> Optional[int]: lowercase : Tuple =full_name.split('''conv_layers.''' )[-1] lowercase : Dict =name.split('''.''' ) lowercase : Union[str, Any] =int(items[0] ) lowercase : int =int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) lowercase : Any =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) lowercase : str =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) lowercase : List[str] =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) lowercase : Any =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def _lowerCAmelCase ( __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : Any , __magic_name__ : Union[str, Any]=None , __magic_name__ : List[str]=None , __magic_name__ : Optional[Any]=None , ) -> Optional[int]: if config_path is not None: lowercase : int =SpeechTaConfig.from_pretrained(__magic_name__ ) else: lowercase : str =SpeechTaConfig() if task == "s2t": lowercase : List[str] =config.max_text_positions lowercase : Union[str, Any] =SpeechTaForSpeechToText(__magic_name__ ) elif task == "t2s": lowercase : Optional[int] =1876 lowercase : Any =600 lowercase : List[str] =config.max_speech_positions lowercase : List[str] =SpeechTaForTextToSpeech(__magic_name__ ) elif task == "s2s": lowercase : Tuple =1876 lowercase : Optional[int] =config.max_speech_positions lowercase : List[Any] =SpeechTaForSpeechToSpeech(__magic_name__ ) else: raise ValueError(f'''Unknown task name: {task}''' ) if vocab_path: lowercase : Any =SpeechTaTokenizer(__magic_name__ , model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it lowercase : str =AddedToken('''<mask>''' , lstrip=__magic_name__ , rstrip=__magic_name__ ) lowercase : Tuple =mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) lowercase : Tuple =SpeechTaFeatureExtractor() lowercase : Union[str, Any] =SpeechTaProcessor(tokenizer=__magic_name__ , feature_extractor=__magic_name__ ) processor.save_pretrained(__magic_name__ ) lowercase : List[str] =torch.load(__magic_name__ ) recursively_load_weights(fairseq_checkpoint['''model'''] , __magic_name__ , __magic_name__ ) model.save_pretrained(__magic_name__ ) if repo_id: print('''Pushing to the hub...''' ) processor.push_to_hub(__magic_name__ ) model.push_to_hub(__magic_name__ ) if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument( """--task""", default="""s2t""", type=str, help="""Type of the SpeechT5 model you'd like to convert. Should be one of 's2t', 't2s', 's2s'.""", ) parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--vocab_path""", default=None, type=str, help="""Path to SentencePiece model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) UpperCamelCase_ = parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
92
'''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 __SCREAMING_SNAKE_CASE : def __init__( self : List[str] , UpperCAmelCase__ : Dict , ): '''simple docstring''' lowercase : Any =parent lowercase : Optional[int] =13 lowercase : Union[str, Any] =7 lowercase : str =30 lowercase : Optional[int] =self.seq_length + self.mem_len lowercase : Dict =15 lowercase : List[str] =True lowercase : Optional[int] =True lowercase : Tuple =99 lowercase : str =[10, 50, 80] lowercase : List[Any] =32 lowercase : Optional[int] =32 lowercase : int =4 lowercase : Any =8 lowercase : List[Any] =128 lowercase : List[str] =2 lowercase : Tuple =2 lowercase : int =None lowercase : Optional[int] =1 lowercase : int =0 lowercase : List[str] =3 lowercase : str =self.vocab_size - 1 lowercase : Tuple =0.01 def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase : Tuple =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase : str =None if self.use_labels: lowercase : Tuple =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase : Union[str, Any] =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 lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' random.seed(self.seed ) tf.random.set_seed(self.seed ) def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] ): '''simple docstring''' lowercase : Tuple =TFTransfoXLModel(UpperCAmelCase__ ) lowercase , lowercase : Optional[Any] =model(UpperCAmelCase__ ).to_tuple() lowercase : List[str] ={'''input_ids''': input_ids_a, '''mems''': mems_a} lowercase , lowercase : Any =model(UpperCAmelCase__ ).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 lowerCamelCase_ ( self : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ): '''simple docstring''' lowercase : int =TFTransfoXLLMHeadModel(UpperCAmelCase__ ) lowercase , lowercase : Tuple =model(UpperCAmelCase__ ).to_tuple() lowercase : Optional[Any] ={'''input_ids''': input_ids_a, '''labels''': lm_labels} lowercase , lowercase : Optional[int] =model(UpperCAmelCase__ ).to_tuple() lowercase , lowercase : List[str] =model([input_ids_a, mems_a] ).to_tuple() lowercase : int ={'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels} lowercase , lowercase : str =model(UpperCAmelCase__ ).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 lowerCamelCase_ ( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ): '''simple docstring''' lowercase : Optional[int] =TFTransfoXLForSequenceClassification(UpperCAmelCase__ ) lowercase : Union[str, Any] =model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase : List[Any] =self.prepare_config_and_inputs() ((lowercase) , (lowercase) , (lowercase) , (lowercase)) : Optional[Any] =config_and_inputs lowercase : Union[str, Any] ={'''input_ids''': input_ids_a} return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ): lowerCamelCase_ = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) lowerCamelCase_ = () if is_tf_available() else () lowerCamelCase_ = ( { '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 lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def lowerCamelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int ): '''simple docstring''' 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 lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : Any =TFTransfoXLModelTester(self ) lowercase : Optional[int] =ConfigTester(self , config_class=UpperCAmelCase__ , d_embed=37 ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' self.model_tester.set_seed() lowercase : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' self.model_tester.set_seed() lowercase : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' lowercase , lowercase : Tuple =self.model_tester.prepare_config_and_inputs_for_common() lowercase : int =[TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: lowercase : str =model_class(UpperCAmelCase__ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: lowercase : Union[str, Any] =model.get_output_embeddings() assert isinstance(UpperCAmelCase__ , tf.keras.layers.Layer ) lowercase : Any =model.get_bias() assert name is None else: lowercase : Optional[int] =model.get_output_embeddings() assert x is None lowercase : Optional[int] =model.get_bias() assert name is None def lowerCamelCase_ ( self : Any ): '''simple docstring''' # TODO JP: Make TransfoXL XLA compliant pass @slow def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : int =TFTransfoXLModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @unittest.skip(reason='''This model doesn\'t play well with fit() due to not returning a single loss.''' ) def lowerCamelCase_ ( self : int ): '''simple docstring''' pass @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @unittest.skip('''Skip test until #12651 is resolved.''' ) @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase : Optional[Any] =TFTransfoXLLMHeadModel.from_pretrained('''transfo-xl-wt103''' ) # fmt: off lowercase : Tuple =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 lowercase : Optional[int] =[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> lowercase : int =model.generate(UpperCAmelCase__ , max_length=200 , do_sample=UpperCAmelCase__ ) self.assertListEqual(output_ids[0].numpy().tolist() , UpperCAmelCase__ )
92
1
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase_ = """▁""" UpperCamelCase_ = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece class __SCREAMING_SNAKE_CASE ( lowercase__ , unittest.TestCase ): lowerCamelCase_ = BertGenerationTokenizer lowerCamelCase_ = False lowerCamelCase_ = True def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' super().setUp() lowercase : List[str] =BertGenerationTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' lowercase : int ='''<s>''' lowercase : List[Any] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' lowercase : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(UpperCAmelCase__ ) , 1002 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' lowercase : Any =BertGenerationTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) lowercase : Optional[Any] =tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [285, 46, 10, 170, 382] , ) lowercase : Tuple =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) lowercase : List[Any] =tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) lowercase : Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def lowerCamelCase_ ( self : Any ): '''simple docstring''' return BertGenerationTokenizer.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) @slow def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Optional[Any] ='''Hello World!''' lowercase : Dict =[18536, 2260, 101] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Tuple =( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) lowercase : Optional[int] =[ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @require_torch @slow def lowerCamelCase_ ( self : Dict ): '''simple docstring''' import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence lowercase : Union[str, Any] =list(self.big_tokenizer.get_vocab().keys() )[:10] lowercase : Union[str, Any] =''' '''.join(UpperCAmelCase__ ) lowercase : Optional[int] =self.big_tokenizer.encode_plus(UpperCAmelCase__ , return_tensors='''pt''' , return_token_type_ids=UpperCAmelCase__ ) lowercase : Optional[Any] =self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=UpperCAmelCase__ ) lowercase : str =BertGenerationConfig() lowercase : str =BertGenerationEncoder(UpperCAmelCase__ ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**UpperCAmelCase__ ) model(**UpperCAmelCase__ ) @slow def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' # fmt: off lowercase : Optional[Any] ={'''input_ids''': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''google/bert_for_seq_generation_L-24_bbc_encoder''' , revision='''c817d1fd1be2ffa69431227a1fe320544943d4db''' , )
92
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str=13 , UpperCAmelCase__ : Tuple=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[Any]=99 , UpperCAmelCase__ : Any=16 , UpperCAmelCase__ : Optional[Any]=36 , UpperCAmelCase__ : str=6 , UpperCAmelCase__ : Any=6 , UpperCAmelCase__ : Optional[int]=6 , UpperCAmelCase__ : Any=37 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : List[str]=512 , UpperCAmelCase__ : List[str]=16 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : Tuple=None , ): '''simple docstring''' lowercase : str =parent lowercase : int =batch_size lowercase : Any =seq_length lowercase : int =is_training lowercase : str =use_input_mask lowercase : int =use_token_type_ids lowercase : Dict =use_labels lowercase : int =vocab_size lowercase : str =embedding_size lowercase : Union[str, Any] =hidden_size lowercase : Tuple =num_hidden_layers lowercase : Any =num_hidden_groups lowercase : Union[str, Any] =num_attention_heads lowercase : Any =intermediate_size lowercase : Tuple =hidden_act lowercase : Optional[int] =hidden_dropout_prob lowercase : Union[str, Any] =attention_probs_dropout_prob lowercase : List[Any] =max_position_embeddings lowercase : int =type_vocab_size lowercase : int =type_sequence_label_size lowercase : Any =initializer_range lowercase : List[Any] =num_labels lowercase : int =num_choices lowercase : Optional[int] =scope def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : int =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase : Optional[int] =None if self.use_input_mask: lowercase : List[str] =random_attention_mask([self.batch_size, self.seq_length] ) lowercase : Dict =None if self.use_token_type_ids: lowercase : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase : Tuple =None lowercase : Any =None lowercase : Dict =None if self.use_labels: lowercase : int =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase : Optional[Any] =ids_tensor([self.batch_size] , self.num_choices ) lowercase : Any =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return AlbertConfig( 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 , num_hidden_groups=self.num_hidden_groups , ) def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str ): '''simple docstring''' lowercase : int =AlbertModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : int =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) lowercase : Dict =model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) lowercase : int =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 lowerCamelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple ): '''simple docstring''' lowercase : Tuple =AlbertForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : int =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , sentence_order_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int ): '''simple docstring''' lowercase : Tuple =AlbertForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : str =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] ): '''simple docstring''' lowercase : List[str] =AlbertForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : List[str] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ): '''simple docstring''' lowercase : Optional[Any] =self.num_labels lowercase : Any =AlbertForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : Dict =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict ): '''simple docstring''' lowercase : List[Any] =self.num_labels lowercase : str =AlbertForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : int =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] ): '''simple docstring''' lowercase : Optional[int] =self.num_choices lowercase : List[Any] =AlbertForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : List[Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase : int =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase : int =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase : List[str] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : Union[str, Any] =self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) : Dict =config_and_inputs lowercase : Optional[Any] ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ): lowerCamelCase_ = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase_ = ( { 'feature-extraction': AlbertModel, 'fill-mask': AlbertForMaskedLM, 'question-answering': AlbertForQuestionAnswering, 'text-classification': AlbertForSequenceClassification, 'token-classification': AlbertForTokenClassification, 'zero-shot': AlbertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase_ = True def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int=False ): '''simple docstring''' lowercase : Optional[int] =super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): lowercase : Any =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) lowercase : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : Tuple =AlbertModelTester(self ) lowercase : Optional[Any] =ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' lowercase : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : str ): '''simple docstring''' lowercase : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' lowercase : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Optional[int] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowercase : Tuple =type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : str =AlbertModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase : int =AlbertModel.from_pretrained('''albert-base-v2''' ) lowercase : Optional[int] =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) lowercase : Any =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowercase : Any =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] lowercase : int =torch.Size((1, 11, 768) ) self.assertEqual(output.shape , UpperCAmelCase__ ) lowercase : Union[str, Any] =torch.tensor( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
92
1
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : int , __magic_name__ : bool , __magic_name__ : list[int] , __magic_name__ : float ) -> int: if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if len(__magic_name__ ) == 0: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , __magic_name__ , __magic_name__ , __magic_name__ ) , minimax(depth + 1 , node_index * 2 + 1 , __magic_name__ , __magic_name__ , __magic_name__ ) , ) return min( minimax(depth + 1 , node_index * 2 , __magic_name__ , __magic_name__ , __magic_name__ ) , minimax(depth + 1 , node_index * 2 + 1 , __magic_name__ , __magic_name__ , __magic_name__ ) , ) def _lowerCAmelCase ( ) -> None: lowercase : Tuple =[90, 23, 6, 33, 21, 65, 123, 34423] lowercase : str =math.log(len(__magic_name__ ) , 2 ) print('''Optimal value : ''' , end='''''' ) print(minimax(0 , 0 , __magic_name__ , __magic_name__ , __magic_name__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
92
'''simple docstring''' import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ): '''simple docstring''' if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) lowercase : Union[str, Any] =img lowercase : Union[str, Any] =img.shape[1] lowercase : str =img.shape[0] lowercase : Union[str, Any] =dst_width lowercase : str =dst_height lowercase : str =self.src_w / self.dst_w lowercase : Optional[Any] =self.src_h / self.dst_h lowercase : int =( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255 ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' for i in range(self.dst_h ): for j in range(self.dst_w ): lowercase : List[Any] =self.img[self.get_y(UpperCAmelCase__ )][self.get_x(UpperCAmelCase__ )] def lowerCamelCase_ ( self : Tuple , UpperCAmelCase__ : int ): '''simple docstring''' return int(self.ratio_x * x ) def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : int ): '''simple docstring''' return int(self.ratio_y * y ) if __name__ == "__main__": UpperCamelCase_ , UpperCamelCase_ = 800, 600 UpperCamelCase_ = imread("""image_data/lena.jpg""", 1) UpperCamelCase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f'''Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}''', n.output ) waitKey(0) destroyAllWindows()
92
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { """microsoft/beit-base-patch16-224-pt22k""": ( """https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json""" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __SCREAMING_SNAKE_CASE ( lowercase__ ): lowerCamelCase_ = 'beit' def __init__( self : Union[str, Any] , UpperCAmelCase__ : Any=8192 , UpperCAmelCase__ : Optional[int]=768 , UpperCAmelCase__ : Union[str, Any]=12 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : str=3072 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Dict=0.0 , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : str=1E-12 , UpperCAmelCase__ : str=224 , UpperCAmelCase__ : Optional[Any]=16 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : int=False , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[Any]=[3, 5, 7, 11] , UpperCAmelCase__ : List[str]=[1, 2, 3, 6] , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Union[str, Any]=0.4 , UpperCAmelCase__ : List[Any]=256 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Optional[int]=255 , **UpperCAmelCase__ : Tuple , ): '''simple docstring''' super().__init__(**UpperCAmelCase__ ) lowercase : List[str] =vocab_size lowercase : str =hidden_size lowercase : Any =num_hidden_layers lowercase : List[str] =num_attention_heads lowercase : List[Any] =intermediate_size lowercase : Optional[int] =hidden_act lowercase : Optional[int] =hidden_dropout_prob lowercase : Any =attention_probs_dropout_prob lowercase : List[str] =initializer_range lowercase : int =layer_norm_eps lowercase : str =image_size lowercase : Union[str, Any] =patch_size lowercase : Tuple =num_channels lowercase : List[Any] =use_mask_token lowercase : Optional[int] =use_absolute_position_embeddings lowercase : Any =use_relative_position_bias lowercase : int =use_shared_relative_position_bias lowercase : str =layer_scale_init_value lowercase : int =drop_path_rate lowercase : Optional[int] =use_mean_pooling # decode head attributes (semantic segmentation) lowercase : Dict =out_indices lowercase : int =pool_scales # auxiliary head attributes (semantic segmentation) lowercase : Optional[Any] =use_auxiliary_head lowercase : Optional[int] =auxiliary_loss_weight lowercase : Optional[int] =auxiliary_channels lowercase : Any =auxiliary_num_convs lowercase : Tuple =auxiliary_concat_input lowercase : List[Any] =semantic_loss_ignore_index class __SCREAMING_SNAKE_CASE ( lowercase__ ): lowerCamelCase_ = version.parse('1.11' ) @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return 1E-4
92
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( __magic_name__ : list[float] ) -> float: lowercase : Any =0.0_0 lowercase : Tuple =0 for resistor in resistors: if resistor <= 0: lowercase : Dict =f'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__magic_name__ ) first_sum += 1 / float(__magic_name__ ) index += 1 return 1 / first_sum def _lowerCAmelCase ( __magic_name__ : list[float] ) -> float: lowercase : Optional[Any] =0.0_0 lowercase : int =0 for resistor in resistors: sum_r += resistor if resistor < 0: lowercase : Tuple =f'''Resistor at index {index} has a negative value!''' raise ValueError(__magic_name__ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
92
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..utils import cached_file # docstyle-ignore UpperCamelCase_ = """ Human: <<task>> Assistant: """ UpperCamelCase_ = """huggingface-tools/default-prompts""" UpperCamelCase_ = {"""chat""": """chat_prompt_template.txt""", """run""": """run_prompt_template.txt"""} def _lowerCAmelCase ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any="run" ) -> List[str]: if prompt_or_repo_id is None: lowercase : Union[str, Any] =DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search('''\\s''' , __magic_name__ ) is not None: return prompt_or_repo_id lowercase : int =cached_file( __magic_name__ , PROMPT_FILES[mode] , repo_type='''dataset''' , user_agent={'''agent''': agent_name} ) with open(__magic_name__ , '''r''' , encoding='''utf-8''' ) as f: return f.read()
92
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.linear_k""": """encoder.layers.*.self_attn.linear_k""", """self_attn.linear_v""": """encoder.layers.*.self_attn.linear_v""", """self_attn.linear_q""": """encoder.layers.*.self_attn.linear_q""", """self_attn.pos_bias_u""": """encoder.layers.*.self_attn.pos_bias_u""", """self_attn.pos_bias_v""": """encoder.layers.*.self_attn.pos_bias_v""", """self_attn.linear_out""": """encoder.layers.*.self_attn.linear_out""", """self_attn.linear_pos""": """encoder.layers.*.self_attn.linear_pos""", """self_attn.rotary_emb""": """encoder.embed_positions""", """self_attn_layer_norm""": """encoder.layers.*.self_attn_layer_norm""", """conv_module.pointwise_conv1""": """encoder.layers.*.conv_module.pointwise_conv1""", """conv_module.pointwise_conv2""": """encoder.layers.*.conv_module.pointwise_conv2""", """conv_module.depthwise_conv""": """encoder.layers.*.conv_module.depthwise_conv""", """conv_module.batch_norm""": """encoder.layers.*.conv_module.batch_norm""", """conv_module.layer_norm""": """encoder.layers.*.conv_module.layer_norm""", """ffn1.w_1""": """encoder.layers.*.ffn1.intermediate_dense""", """ffn1.w_2""": """encoder.layers.*.ffn1.output_dense""", """ffn1.layer_norm""": """encoder.layers.*.ffn1_layer_norm""", """ffn2.w_1""": """encoder.layers.*.ffn2.intermediate_dense""", """ffn2.w_2""": """encoder.layers.*.ffn2.output_dense""", """ffn2.layer_norm""": """encoder.layers.*.ffn2_layer_norm""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } UpperCamelCase_ = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def _lowerCAmelCase ( __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ) -> str: for attribute in key.split('''.''' ): lowercase : Tuple =getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: lowercase : Optional[int] =getattr(__magic_name__ , __magic_name__ ).shape else: lowercase : List[Any] =hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": lowercase : Any =value elif weight_type == "weight_g": lowercase : List[Any] =value elif weight_type == "weight_v": lowercase : Union[str, Any] =value elif weight_type == "bias": lowercase : Tuple =value elif weight_type == "running_mean": lowercase : Union[str, Any] =value elif weight_type == "running_var": lowercase : str =value elif weight_type == "num_batches_tracked": lowercase : Tuple =value elif weight_type == "inv_freq": lowercase : Optional[Any] =value else: lowercase : Tuple =value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Union[str, Any]: lowercase : Optional[int] =[] lowercase : Tuple =fairseq_model.state_dict() lowercase : List[Any] =hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): lowercase : Tuple =False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == '''group''' , ) lowercase : List[Any] =True else: for key, mapped_key in MAPPING.items(): lowercase : Optional[int] ='''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: lowercase : Union[str, Any] =True if "*" in mapped_key: lowercase : Optional[int] =name.split(__magic_name__ )[0].split('''.''' )[-2] lowercase : List[str] =mapped_key.replace('''*''' , __magic_name__ ) if "pos_bias_u" in name: lowercase : Optional[Any] =None elif "pos_bias_v" in name: lowercase : Union[str, Any] =None elif "weight_g" in name: lowercase : Any ='''weight_g''' elif "weight_v" in name: lowercase : Tuple ='''weight_v''' elif "bias" in name: lowercase : Optional[int] ='''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj lowercase : Optional[int] ='''weight''' elif "running_mean" in name: lowercase : Union[str, Any] ='''running_mean''' elif "inv_freq" in name: lowercase : Any ='''inv_freq''' elif "running_var" in name: lowercase : Tuple ='''running_var''' elif "num_batches_tracked" in name: lowercase : Dict ='''num_batches_tracked''' else: lowercase : str =None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple ) -> int: lowercase : Optional[Any] =full_name.split('''conv_layers.''' )[-1] lowercase : Any =name.split('''.''' ) lowercase : List[str] =int(items[0] ) lowercase : Union[str, Any] =int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) lowercase : Union[str, Any] =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) lowercase : Optional[Any] =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) lowercase : Optional[int] =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) lowercase : str =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def _lowerCAmelCase ( __magic_name__ : List[str] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=None , __magic_name__ : Union[str, Any]=True ) -> Union[str, Any]: if config_path is not None: lowercase : Optional[Any] =WavaVecaConformerConfig.from_pretrained(__magic_name__ , hidden_act='''swish''' ) else: lowercase : Optional[int] =WavaVecaConformerConfig() if "rope" in checkpoint_path: lowercase : Dict ='''rotary''' if is_finetuned: if dict_path: lowercase : Optional[Any] =Dictionary.load(__magic_name__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowercase : str =target_dict.pad_index lowercase : Union[str, Any] =target_dict.bos_index lowercase : Any =target_dict.eos_index lowercase : Tuple =len(target_dict.symbols ) lowercase : str =os.path.join(__magic_name__ , '''vocab.json''' ) if not os.path.isdir(__magic_name__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__magic_name__ ) ) return os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) lowercase : Dict =target_dict.indices # fairseq has the <pad> and <s> switched lowercase : str =0 lowercase : List[Any] =1 with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(__magic_name__ , __magic_name__ ) lowercase : List[str] =WavaVecaCTCTokenizer( __magic_name__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=__magic_name__ , ) lowercase : Optional[int] =True if config.feat_extract_norm == '''layer''' else False lowercase : str =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__magic_name__ , return_attention_mask=__magic_name__ , ) lowercase : Tuple =WavaVecaProcessor(feature_extractor=__magic_name__ , tokenizer=__magic_name__ ) processor.save_pretrained(__magic_name__ ) lowercase : str =WavaVecaConformerForCTC(__magic_name__ ) else: lowercase : Tuple =WavaVecaConformerForPreTraining(__magic_name__ ) if is_finetuned: lowercase , lowercase , lowercase : Optional[int] =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: lowercase : Dict =argparse.Namespace(task='''audio_pretraining''' ) lowercase : Optional[int] =fairseq.tasks.setup_task(__magic_name__ ) lowercase , lowercase , lowercase : str =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__magic_name__ ) lowercase : List[Any] =model[0].eval() recursively_load_weights(__magic_name__ , __magic_name__ , not is_finetuned ) hf_wavavec.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase_ = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
92
1
'''simple docstring''' import numpy as np def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : int , __magic_name__ : str ) -> List[str]: lowercase : str =int(np.ceil((x_end - xa) / h ) ) lowercase : Optional[Any] =np.zeros((n + 1,) ) lowercase : Optional[int] =ya lowercase : List[Any] =xa for k in range(__magic_name__ ): lowercase : str =f(__magic_name__ , y[k] ) lowercase : Optional[int] =f(x + 0.5 * h , y[k] + 0.5 * h * ka ) lowercase : List[str] =f(x + 0.5 * h , y[k] + 0.5 * h * ka ) lowercase : Optional[int] =f(x + h , y[k] + h * ka ) lowercase : List[Any] =y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
92
'''simple docstring''' import math import flax.linen as nn import jax.numpy as jnp def _lowerCAmelCase ( __magic_name__ : jnp.ndarray , __magic_name__ : int , __magic_name__ : float = 1 , __magic_name__ : float = 1 , __magic_name__ : float = 1.0E4 , __magic_name__ : bool = False , __magic_name__ : float = 1.0 , ) -> jnp.ndarray: assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, f'''Embedding dimension {embedding_dim} should be even''' lowercase : int =float(embedding_dim // 2 ) lowercase : Optional[int] =math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) lowercase : Any =min_timescale * jnp.exp(jnp.arange(__magic_name__ , dtype=jnp.floataa ) * -log_timescale_increment ) lowercase : List[Any] =jnp.expand_dims(__magic_name__ , 1 ) * jnp.expand_dims(__magic_name__ , 0 ) # scale embeddings lowercase : Tuple =scale * emb if flip_sin_to_cos: lowercase : Dict =jnp.concatenate([jnp.cos(__magic_name__ ), jnp.sin(__magic_name__ )] , axis=1 ) else: lowercase : Any =jnp.concatenate([jnp.sin(__magic_name__ ), jnp.cos(__magic_name__ )] , axis=1 ) lowercase : List[str] =jnp.reshape(__magic_name__ , [jnp.shape(__magic_name__ )[0], embedding_dim] ) return signal class __SCREAMING_SNAKE_CASE ( nn.Module ): lowerCamelCase_ = 32 lowerCamelCase_ = jnp.floataa @nn.compact def __call__( self : Tuple , UpperCAmelCase__ : int ): '''simple docstring''' lowercase : List[Any] =nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_1''' )(UpperCAmelCase__ ) lowercase : Any =nn.silu(UpperCAmelCase__ ) lowercase : int =nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_2''' )(UpperCAmelCase__ ) return temb class __SCREAMING_SNAKE_CASE ( nn.Module ): lowerCamelCase_ = 32 lowerCamelCase_ = False lowerCamelCase_ = 1 @nn.compact def __call__( self : int , UpperCAmelCase__ : str ): '''simple docstring''' return get_sinusoidal_embeddings( UpperCAmelCase__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
92
1
'''simple docstring''' import requests from bsa import BeautifulSoup def _lowerCAmelCase ( __magic_name__ : str = "https://www.worldometers.info/coronavirus" ) -> dict: lowercase : List[Any] =BeautifulSoup(requests.get(__magic_name__ ).text , '''html.parser''' ) lowercase : Tuple =soup.findAll('''h1''' ) lowercase : int =soup.findAll('''div''' , {'''class''': '''maincounter-number'''} ) keys += soup.findAll('''span''' , {'''class''': '''panel-title'''} ) values += soup.findAll('''div''' , {'''class''': '''number-table-main'''} ) return {key.text.strip(): value.text.strip() for key, value in zip(__magic_name__ , __magic_name__ )} if __name__ == "__main__": print("""\033[1m""" + """COVID-19 Status of the World""" + """\033[0m\n""") for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
92
'''simple docstring''' from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) # TODO Update this UpperCamelCase_ = { """facebook/esm-1b""": """https://huggingface.co/facebook/esm-1b/resolve/main/config.json""", # See all ESM models at https://huggingface.co/models?filter=esm } class __SCREAMING_SNAKE_CASE ( lowercase__ ): lowerCamelCase_ = 'esm' def __init__( self : Optional[Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=768 , UpperCAmelCase__ : Union[str, Any]=12 , UpperCAmelCase__ : List[Any]=12 , UpperCAmelCase__ : Optional[Any]=3072 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=1026 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : List[Any]="absolute" , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : str=False , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : int , ): '''simple docstring''' super().__init__(pad_token_id=UpperCAmelCase__ , mask_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) lowercase : Any =vocab_size lowercase : List[Any] =hidden_size lowercase : Any =num_hidden_layers lowercase : Optional[Any] =num_attention_heads lowercase : Tuple =intermediate_size lowercase : int =hidden_dropout_prob lowercase : Dict =attention_probs_dropout_prob lowercase : Optional[int] =max_position_embeddings lowercase : Union[str, Any] =initializer_range lowercase : Tuple =layer_norm_eps lowercase : Union[str, Any] =position_embedding_type lowercase : List[Any] =use_cache lowercase : Dict =emb_layer_norm_before lowercase : Optional[Any] =token_dropout lowercase : Union[str, Any] =is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) lowercase : Any =EsmFoldConfig() elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): lowercase : Optional[int] =EsmFoldConfig(**UpperCAmelCase__ ) lowercase : Union[str, Any] =esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) lowercase : int =get_default_vocab_list() else: lowercase : Tuple =vocab_list else: lowercase : Union[str, Any] =None lowercase : Dict =None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , UpperCAmelCase__ ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : Union[str, Any] =super().to_dict() if isinstance(self.esmfold_config , UpperCAmelCase__ ): lowercase : Optional[Any] =self.esmfold_config.to_dict() return output @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = None lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = 0 lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = 1_28 lowerCamelCase_ = None def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' if self.trunk is None: lowercase : str =TrunkConfig() elif isinstance(self.trunk , UpperCAmelCase__ ): lowercase : int =TrunkConfig(**self.trunk ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : str =asdict(self ) lowercase : Union[str, Any] =self.trunk.to_dict() return output @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = 48 lowerCamelCase_ = 10_24 lowerCamelCase_ = 1_28 lowerCamelCase_ = 32 lowerCamelCase_ = 32 lowerCamelCase_ = 32 lowerCamelCase_ = 0 lowerCamelCase_ = 0 lowerCamelCase_ = False lowerCamelCase_ = 4 lowerCamelCase_ = 1_28 lowerCamelCase_ = None def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' if self.structure_module is None: lowercase : Any =StructureModuleConfig() elif isinstance(self.structure_module , UpperCAmelCase__ ): lowercase : Union[str, Any] =StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(F'''`max_recycles` should be positive, got {self.max_recycles}.''' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' F''' {self.sequence_state_dim} and {self.sequence_state_dim}.''' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' F''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.''' ) lowercase : str =self.sequence_state_dim // self.sequence_head_width lowercase : int =self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' F''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.''' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' F''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.''' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(F'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.''' ) if self.dropout >= 0.4: raise ValueError(F'''`dropout` should not be greater than 0.4, got {self.dropout}.''' ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' lowercase : List[Any] =asdict(self ) lowercase : Any =self.structure_module.to_dict() return output @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = 3_84 lowerCamelCase_ = 1_28 lowerCamelCase_ = 16 lowerCamelCase_ = 1_28 lowerCamelCase_ = 12 lowerCamelCase_ = 4 lowerCamelCase_ = 8 lowerCamelCase_ = 0.1 lowerCamelCase_ = 8 lowerCamelCase_ = 1 lowerCamelCase_ = 2 lowerCamelCase_ = 7 lowerCamelCase_ = 10 lowerCamelCase_ = 1E-8 lowerCamelCase_ = 1E5 def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return asdict(self ) def _lowerCAmelCase ( ) -> Optional[int]: return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
92
1
'''simple docstring''' def _lowerCAmelCase ( __magic_name__ : int ) -> None: lowercase : int =generate_pascal_triangle(__magic_name__ ) for row_idx in range(__magic_name__ ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=''' ''' ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=''' ''' ) else: print(triangle[row_idx][col_idx] , end='''''' ) print() def _lowerCAmelCase ( __magic_name__ : int ) -> list[list[int]]: if not isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''The input value of \'num_rows\' should be \'int\'''' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( '''The input value of \'num_rows\' should be greater than or equal to 0''' ) lowercase : list[list[int]] =[] for current_row_idx in range(__magic_name__ ): lowercase : List[str] =populate_current_row(__magic_name__ , __magic_name__ ) triangle.append(__magic_name__ ) return triangle def _lowerCAmelCase ( __magic_name__ : list[list[int]] , __magic_name__ : int ) -> list[int]: lowercase : int =[-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 lowercase , lowercase : Any =1, 1 for current_col_idx in range(1 , __magic_name__ ): calculate_current_element( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) return current_row def _lowerCAmelCase ( __magic_name__ : list[list[int]] , __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : int , ) -> None: lowercase : Any =triangle[current_row_idx - 1][current_col_idx - 1] lowercase : Union[str, Any] =triangle[current_row_idx - 1][current_col_idx] lowercase : int =above_to_left_elt + above_to_right_elt def _lowerCAmelCase ( __magic_name__ : int ) -> list[list[int]]: if not isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''The input value of \'num_rows\' should be \'int\'''' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( '''The input value of \'num_rows\' should be greater than or equal to 0''' ) lowercase : list[list[int]] =[[1]] for row_index in range(1 , __magic_name__ ): lowercase : List[str] =[0] + result[-1] + [0] lowercase : Tuple =row_index + 1 # Calculate the number of distinct elements in a row lowercase : List[Any] =sum(divmod(__magic_name__ , 2 ) ) lowercase : int =[ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] lowercase : Union[str, Any] =row_first_half[: (row_index + 1) // 2] row_second_half.reverse() lowercase : str =row_first_half + row_second_half result.append(__magic_name__ ) return result def _lowerCAmelCase ( ) -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(__magic_name__ : Callable , __magic_name__ : int ) -> None: lowercase : str =f'''{func.__name__}({value})''' lowercase : Optional[Any] =timeit(f'''__main__.{call}''' , setup='''import __main__''' ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f'''{call:38} -- {timing:.4f} seconds''' ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(__magic_name__ , __magic_name__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
92
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # 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(__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 _lowerCAmelCase ( __magic_name__ : int ) -> Tuple: config.addinivalue_line( '''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' ) config.addinivalue_line( '''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' ) config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' ) config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' ) config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' ) config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' ) def _lowerCAmelCase ( __magic_name__ : int ) -> Any: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(__magic_name__ ) def _lowerCAmelCase ( __magic_name__ : Any ) -> Any: from transformers.testing_utils import pytest_terminal_summary_main lowercase : Optional[Any] =terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__magic_name__ , id=__magic_name__ ) def _lowerCAmelCase ( __magic_name__ : Tuple , __magic_name__ : Union[str, Any] ) -> List[str]: # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: lowercase : Optional[int] =0 # Doctest custom flag to ignore output. UpperCamelCase_ = doctest.register_optionflag("""IGNORE_RESULT""") UpperCamelCase_ = doctest.OutputChecker class __SCREAMING_SNAKE_CASE ( lowercase__ ): def lowerCamelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] ): '''simple docstring''' if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_ = CustomOutputChecker UpperCamelCase_ = HfDoctestModule UpperCamelCase_ = HfDocTestParser
92
1
'''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 __SCREAMING_SNAKE_CASE ( unittest.TestCase ): lowerCamelCase_ = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING lowerCamelCase_ = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ): '''simple docstring''' lowercase : str =AudioClassificationPipeline(model=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ ) # test with a raw waveform lowercase : Dict =np.zeros((34000,) ) lowercase : List[Any] =np.zeros((14000,) ) return audio_classifier, [audioa, audio] def lowerCamelCase_ ( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ): '''simple docstring''' lowercase , lowercase : Union[str, Any] =examples lowercase : Union[str, Any] =audio_classifier(UpperCAmelCase__ ) # by default a model is initialized with num_labels=2 self.assertEqual( UpperCAmelCase__ , [ {'''score''': ANY(UpperCAmelCase__ ), '''label''': ANY(UpperCAmelCase__ )}, {'''score''': ANY(UpperCAmelCase__ ), '''label''': ANY(UpperCAmelCase__ )}, ] , ) lowercase : List[str] =audio_classifier(UpperCAmelCase__ , top_k=1 ) self.assertEqual( UpperCAmelCase__ , [ {'''score''': ANY(UpperCAmelCase__ ), '''label''': ANY(UpperCAmelCase__ )}, ] , ) self.run_torchaudio(UpperCAmelCase__ ) @require_torchaudio def lowerCamelCase_ ( self : str , UpperCAmelCase__ : Optional[int] ): '''simple docstring''' import datasets # test with a local file lowercase : Optional[int] =datasets.load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) lowercase : str =dataset[0]['''audio''']['''array'''] lowercase : Tuple =audio_classifier(UpperCAmelCase__ ) self.assertEqual( UpperCAmelCase__ , [ {'''score''': ANY(UpperCAmelCase__ ), '''label''': ANY(UpperCAmelCase__ )}, {'''score''': ANY(UpperCAmelCase__ ), '''label''': ANY(UpperCAmelCase__ )}, ] , ) @require_torch def lowerCamelCase_ ( self : str ): '''simple docstring''' lowercase : List[Any] ='''anton-l/wav2vec2-random-tiny-classifier''' lowercase : Any =pipeline('''audio-classification''' , model=UpperCAmelCase__ ) lowercase : Any =np.ones((8000,) ) lowercase : Tuple =audio_classifier(UpperCAmelCase__ , top_k=4 ) lowercase : Any =[ {'''score''': 0.08_42, '''label''': '''no'''}, {'''score''': 0.08_38, '''label''': '''up'''}, {'''score''': 0.08_37, '''label''': '''go'''}, {'''score''': 0.08_34, '''label''': '''right'''}, ] lowercase : str =[ {'''score''': 0.08_45, '''label''': '''stop'''}, {'''score''': 0.08_44, '''label''': '''on'''}, {'''score''': 0.08_41, '''label''': '''right'''}, {'''score''': 0.08_34, '''label''': '''left'''}, ] self.assertIn(nested_simplify(UpperCAmelCase__ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) lowercase : Optional[int] ={'''array''': np.ones((8000,) ), '''sampling_rate''': audio_classifier.feature_extractor.sampling_rate} lowercase : Union[str, Any] =audio_classifier(UpperCAmelCase__ , top_k=4 ) self.assertIn(nested_simplify(UpperCAmelCase__ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def lowerCamelCase_ ( self : Any ): '''simple docstring''' import datasets lowercase : List[Any] ='''superb/wav2vec2-base-superb-ks''' lowercase : str =pipeline('''audio-classification''' , model=UpperCAmelCase__ ) lowercase : Optional[int] =datasets.load_dataset('''anton-l/superb_dummy''' , '''ks''' , split='''test''' ) lowercase : Optional[int] =np.array(dataset[3]['''speech'''] , dtype=np.floataa ) lowercase : Optional[Any] =audio_classifier(UpperCAmelCase__ , top_k=4 ) self.assertEqual( nested_simplify(UpperCAmelCase__ , decimals=3 ) , [ {'''score''': 0.9_81, '''label''': '''go'''}, {'''score''': 0.0_07, '''label''': '''up'''}, {'''score''': 0.0_06, '''label''': '''_unknown_'''}, {'''score''': 0.0_01, '''label''': '''down'''}, ] , ) @require_tf @unittest.skip('''Audio classification is not implemented for TF''' ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' pass
92
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging UpperCamelCase_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( lowercase__ ): lowerCamelCase_ = ['pixel_values'] def __init__( self : List[Any] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[int, float] = 1 / 255 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 8 , **UpperCAmelCase__ : str , ): '''simple docstring''' super().__init__(**UpperCAmelCase__ ) lowercase : Union[str, Any] =do_rescale lowercase : List[Any] =rescale_factor lowercase : Tuple =do_pad lowercase : List[str] =pad_size def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Optional[int] ): '''simple docstring''' return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCamelCase_ ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None ): '''simple docstring''' lowercase , lowercase : Union[str, Any] =get_image_size(UpperCAmelCase__ ) lowercase : Tuple =(old_height // size + 1) * size - old_height lowercase : Tuple =(old_width // size + 1) * size - old_width return pad(UpperCAmelCase__ , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[float] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCAmelCase__ : Optional[Any] , ): '''simple docstring''' lowercase : int =do_rescale if do_rescale is not None else self.do_rescale lowercase : Tuple =rescale_factor if rescale_factor is not None else self.rescale_factor lowercase : int =do_pad if do_pad is not None else self.do_pad lowercase : List[Any] =pad_size if pad_size is not None else self.pad_size lowercase : Any =make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. lowercase : Dict =[to_numpy_array(UpperCAmelCase__ ) for image in images] if do_rescale: lowercase : Tuple =[self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images] if do_pad: lowercase : Union[str, Any] =[self.pad(UpperCAmelCase__ , size=UpperCAmelCase__ ) for image in images] lowercase : Dict =[to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] lowercase : Any ={'''pixel_values''': images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
92
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json""", """allenai/longformer-large-4096""": """https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json""", """allenai/longformer-large-4096-finetuned-triviaqa""": ( """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json""" ), """allenai/longformer-base-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json""" ), """allenai/longformer-large-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json""" ), } class __SCREAMING_SNAKE_CASE ( lowercase__ ): lowerCamelCase_ = 'longformer' def __init__( self : List[str] , UpperCAmelCase__ : Union[List[int], int] = 512 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 0 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 30522 , UpperCAmelCase__ : int = 768 , UpperCAmelCase__ : int = 12 , UpperCAmelCase__ : int = 12 , UpperCAmelCase__ : int = 3072 , UpperCAmelCase__ : str = "gelu" , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : float = 0.02 , UpperCAmelCase__ : float = 1E-12 , UpperCAmelCase__ : bool = False , **UpperCAmelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) lowercase : Dict =attention_window lowercase : Any =sep_token_id lowercase : List[Any] =bos_token_id lowercase : Optional[int] =eos_token_id lowercase : List[str] =vocab_size lowercase : Any =hidden_size lowercase : Optional[int] =num_hidden_layers lowercase : Optional[Any] =num_attention_heads lowercase : List[Any] =hidden_act lowercase : Optional[int] =intermediate_size lowercase : str =hidden_dropout_prob lowercase : str =attention_probs_dropout_prob lowercase : Tuple =max_position_embeddings lowercase : List[Any] =type_vocab_size lowercase : Optional[Any] =initializer_range lowercase : int =layer_norm_eps lowercase : List[Any] =onnx_export class __SCREAMING_SNAKE_CASE ( lowercase__ ): def __init__( self : Any , UpperCAmelCase__ : "PretrainedConfig" , UpperCAmelCase__ : str = "default" , UpperCAmelCase__ : "List[PatchingSpec]" = None ): '''simple docstring''' super().__init__(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) lowercase : Tuple =True @property def lowerCamelCase_ ( self : int ): '''simple docstring''' if self.task == "multiple-choice": lowercase : Optional[Any] ={0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowercase : Union[str, Any] ={0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''global_attention_mask''', dynamic_axis), ] ) @property def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : Any =super().outputs if self.task == "default": lowercase : List[Any] ={0: '''batch'''} return outputs @property def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return 1E-4 @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 14 ) def lowerCamelCase_ ( self : str , UpperCAmelCase__ : "PreTrainedTokenizerBase" , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[TensorType] = None , ): '''simple docstring''' lowercase : Optional[int] =super().generate_dummy_inputs( preprocessor=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , seq_length=UpperCAmelCase__ , is_pair=UpperCAmelCase__ , framework=UpperCAmelCase__ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly lowercase : Any =torch.zeros_like(inputs['''input_ids'''] ) # make every second token global lowercase : List[str] =1 return inputs
92
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ """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 UpperCamelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
1
'''simple docstring''' def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : int ) -> int: return int(input_a == input_a == 0 ) def _lowerCAmelCase ( ) -> None: print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(f'''| 0 | 0 | {nor_gate(0 , 0 )} |''' ) print(f'''| 0 | 1 | {nor_gate(0 , 1 )} |''' ) print(f'''| 1 | 0 | {nor_gate(1 , 0 )} |''' ) print(f'''| 1 | 1 | {nor_gate(1 , 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
92
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase_ = {"""tokenization_byt5""": ["""ByT5Tokenizer"""]} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
1
'''simple docstring''' import numpy as np import datasets UpperCamelCase_ = """ Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. Mahalanobis in 1936 and has been used in various statistical applications ever since [source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/] """ UpperCamelCase_ = """\ @article{de2000mahalanobis, title={The mahalanobis distance}, author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L}, journal={Chemometrics and intelligent laboratory systems}, volume={50}, number={1}, pages={1--18}, year={2000}, publisher={Elsevier} } """ UpperCamelCase_ = """ Args: X: List of datapoints to be compared with the `reference_distribution`. reference_distribution: List of datapoints from the reference distribution we want to compare to. Returns: mahalanobis: The Mahalonobis distance for each datapoint in `X`. Examples: >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\") >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]]) >>> print(results) {'mahalanobis': array([0.5])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def lowerCamelCase_ ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''X''': datasets.Sequence(datasets.Value('''float''' , id='''sequence''' ) , id='''X''' ), } ) , ) def lowerCamelCase_ ( self : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str ): '''simple docstring''' # convert to numpy arrays lowercase : Optional[Any] =np.array(UpperCAmelCase__ ) lowercase : List[str] =np.array(UpperCAmelCase__ ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('''Expected `X` to be a 2D vector''' ) if len(reference_distribution.shape ) != 2: raise ValueError('''Expected `reference_distribution` to be a 2D vector''' ) if reference_distribution.shape[0] < 2: raise ValueError( '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''' ) # Get mahalanobis distance for each prediction lowercase : Tuple =X - np.mean(UpperCAmelCase__ ) lowercase : int =np.cov(reference_distribution.T ) try: lowercase : Dict =np.linalg.inv(UpperCAmelCase__ ) except np.linalg.LinAlgError: lowercase : Optional[Any] =np.linalg.pinv(UpperCAmelCase__ ) lowercase : int =np.dot(UpperCAmelCase__ , UpperCAmelCase__ ) lowercase : Any =np.dot(UpperCAmelCase__ , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
92
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase_ = logging.getLogger(__name__) def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : str ) -> Union[str, Any]: return (preds == labels).mean() @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} ) lowerCamelCase_ = field(metadata={'help': 'Should contain the data files for the task.'} ) lowerCamelCase_ = field( default=1_28 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def _lowerCAmelCase ( ) -> int: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase : Dict =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowercase , lowercase , lowercase : List[Any] =parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , __magic_name__ ) # Set seed set_seed(training_args.seed ) try: lowercase : Any =processors[data_args.task_name]() lowercase : Optional[int] =processor.get_labels() lowercase : str =len(__magic_name__ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase : List[str] =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__magic_name__ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) lowercase : int =AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) lowercase : Any =AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , ) # Get datasets lowercase : int =( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowercase : Union[str, Any] =( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(__magic_name__ : EvalPrediction ) -> Dict: lowercase : Dict =np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(__magic_name__ , p.label_ids )} # Data collator lowercase : List[str] =DataCollatorWithPadding(__magic_name__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowercase : Dict =Trainer( model=__magic_name__ , args=__magic_name__ , train_dataset=__magic_name__ , eval_dataset=__magic_name__ , compute_metrics=__magic_name__ , data_collator=__magic_name__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowercase : Optional[Any] ={} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowercase : List[Any] =trainer.evaluate() lowercase : Any =os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(__magic_name__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , __magic_name__ , __magic_name__ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__magic_name__ ) return results def _lowerCAmelCase ( __magic_name__ : Any ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
92
1
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed UpperCamelCase_ = { """distilbert""": (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), """roberta""": (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), """bert""": (BertConfig, BertForMaskedLM, BertTokenizer), """gpt2""": (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def _lowerCAmelCase ( __magic_name__ : List[Any] ) -> List[Any]: assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : Optional[int] ) -> Tuple: if args.student_type == "roberta": lowercase : List[Any] =False elif args.student_type == "gpt2": lowercase : Dict =False def _lowerCAmelCase ( __magic_name__ : Optional[int] , __magic_name__ : int ) -> str: if args.student_type == "roberta": lowercase : str =False def _lowerCAmelCase ( ) -> List[Any]: lowercase : int =argparse.ArgumentParser(description='''Training''' ) parser.add_argument('''--force''' , action='''store_true''' , help='''Overwrite dump_path if it already exists.''' ) parser.add_argument( '''--dump_path''' , type=__magic_name__ , required=__magic_name__ , help='''The output directory (log, checkpoints, parameters, etc.)''' ) parser.add_argument( '''--data_file''' , type=__magic_name__ , required=__magic_name__ , help='''The binarized file (tokenized + tokens_to_ids) and grouped by sequence.''' , ) parser.add_argument( '''--student_type''' , type=__magic_name__ , choices=['''distilbert''', '''roberta''', '''gpt2'''] , required=__magic_name__ , help='''The student type (DistilBERT, RoBERTa).''' , ) parser.add_argument('''--student_config''' , type=__magic_name__ , required=__magic_name__ , help='''Path to the student configuration.''' ) parser.add_argument( '''--student_pretrained_weights''' , default=__magic_name__ , type=__magic_name__ , help='''Load student initialization checkpoint.''' ) parser.add_argument( '''--teacher_type''' , choices=['''bert''', '''roberta''', '''gpt2'''] , required=__magic_name__ , help='''Teacher type (BERT, RoBERTa).''' ) parser.add_argument('''--teacher_name''' , type=__magic_name__ , required=__magic_name__ , help='''The teacher model.''' ) parser.add_argument('''--temperature''' , default=2.0 , type=__magic_name__ , help='''Temperature for the softmax temperature.''' ) parser.add_argument( '''--alpha_ce''' , default=0.5 , type=__magic_name__ , help='''Linear weight for the distillation loss. Must be >=0.''' ) parser.add_argument( '''--alpha_mlm''' , default=0.0 , type=__magic_name__ , help='''Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.''' , ) parser.add_argument('''--alpha_clm''' , default=0.5 , type=__magic_name__ , help='''Linear weight for the CLM loss. Must be >=0.''' ) parser.add_argument('''--alpha_mse''' , default=0.0 , type=__magic_name__ , help='''Linear weight of the MSE loss. Must be >=0.''' ) parser.add_argument( '''--alpha_cos''' , default=0.0 , type=__magic_name__ , help='''Linear weight of the cosine embedding loss. Must be >=0.''' ) parser.add_argument( '''--mlm''' , action='''store_true''' , help='''The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.''' ) parser.add_argument( '''--mlm_mask_prop''' , default=0.1_5 , type=__magic_name__ , help='''Proportion of tokens for which we need to make a prediction.''' , ) parser.add_argument('''--word_mask''' , default=0.8 , type=__magic_name__ , help='''Proportion of tokens to mask out.''' ) parser.add_argument('''--word_keep''' , default=0.1 , type=__magic_name__ , help='''Proportion of tokens to keep.''' ) parser.add_argument('''--word_rand''' , default=0.1 , type=__magic_name__ , help='''Proportion of tokens to randomly replace.''' ) parser.add_argument( '''--mlm_smoothing''' , default=0.7 , type=__magic_name__ , help='''Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).''' , ) parser.add_argument('''--token_counts''' , type=__magic_name__ , help='''The token counts in the data_file for MLM.''' ) parser.add_argument( '''--restrict_ce_to_mask''' , action='''store_true''' , help='''If true, compute the distillation loss only the [MLM] prediction distribution.''' , ) parser.add_argument( '''--freeze_pos_embs''' , action='''store_true''' , help='''Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.''' , ) parser.add_argument( '''--freeze_token_type_embds''' , action='''store_true''' , help='''Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.''' , ) parser.add_argument('''--n_epoch''' , type=__magic_name__ , default=3 , help='''Number of pass on the whole dataset.''' ) parser.add_argument('''--batch_size''' , type=__magic_name__ , default=5 , help='''Batch size (for each process).''' ) parser.add_argument( '''--group_by_size''' , action='''store_false''' , help='''If true, group sequences that have similar length into the same batch. Default is true.''' , ) parser.add_argument( '''--gradient_accumulation_steps''' , type=__magic_name__ , default=50 , help='''Gradient accumulation for larger training batches.''' , ) parser.add_argument('''--warmup_prop''' , default=0.0_5 , type=__magic_name__ , help='''Linear warmup proportion.''' ) parser.add_argument('''--weight_decay''' , default=0.0 , type=__magic_name__ , help='''Weight decay if we apply some.''' ) parser.add_argument('''--learning_rate''' , default=5E-4 , type=__magic_name__ , help='''The initial learning rate for Adam.''' ) parser.add_argument('''--adam_epsilon''' , default=1E-6 , type=__magic_name__ , help='''Epsilon for Adam optimizer.''' ) parser.add_argument('''--max_grad_norm''' , default=5.0 , type=__magic_name__ , help='''Max gradient norm.''' ) parser.add_argument('''--initializer_range''' , default=0.0_2 , type=__magic_name__ , help='''Random initialization range.''' ) parser.add_argument( '''--fp16''' , action='''store_true''' , help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit''' , ) parser.add_argument( '''--fp16_opt_level''' , type=__magic_name__ , default='''O1''' , help=( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].''' '''See details at https://nvidia.github.io/apex/amp.html''' ) , ) parser.add_argument('''--n_gpu''' , type=__magic_name__ , default=1 , help='''Number of GPUs in the node.''' ) parser.add_argument('''--local_rank''' , type=__magic_name__ , default=-1 , help='''Distributed training - Local rank''' ) parser.add_argument('''--seed''' , type=__magic_name__ , default=56 , help='''Random seed''' ) parser.add_argument('''--log_interval''' , type=__magic_name__ , default=500 , help='''Tensorboard logging interval.''' ) parser.add_argument('''--checkpoint_interval''' , type=__magic_name__ , default=4000 , help='''Checkpoint interval.''' ) lowercase : Dict =parser.parse_args() sanity_checks(__magic_name__ ) # ARGS # init_gpu_params(__magic_name__ ) set_seed(__magic_name__ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite''' ''' itUse `--force` if you want to overwrite it''' ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f'''Experiment will be dumped and logged in {args.dump_path}''' ) # SAVE PARAMS # logger.info(f'''Param: {args}''' ) with open(os.path.join(args.dump_path , '''parameters.json''' ) , '''w''' ) as f: json.dump(vars(__magic_name__ ) , __magic_name__ , indent=4 ) git_log(args.dump_path ) lowercase , lowercase , lowercase : Optional[int] =MODEL_CLASSES[args.student_type] lowercase , lowercase , lowercase : str =MODEL_CLASSES[args.teacher_type] # TOKENIZER # lowercase : Optional[Any] =teacher_tokenizer_class.from_pretrained(args.teacher_name ) lowercase : Tuple ={} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): lowercase : List[str] =tokenizer.all_special_tokens.index(__magic_name__ ) lowercase : int =tokenizer.all_special_ids[idx] logger.info(f'''Special tokens {special_tok_ids}''' ) lowercase : Optional[int] =special_tok_ids lowercase : str =tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f'''Loading data from {args.data_file}''' ) with open(args.data_file , '''rb''' ) as fp: lowercase : List[str] =pickle.load(__magic_name__ ) if args.mlm: logger.info(f'''Loading token counts from {args.token_counts} (already pre-computed)''' ) with open(args.token_counts , '''rb''' ) as fp: lowercase : Optional[Any] =pickle.load(__magic_name__ ) lowercase : Optional[int] =np.maximum(__magic_name__ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): lowercase : Optional[Any] =0.0 # do not predict special tokens lowercase : Any =torch.from_numpy(__magic_name__ ) else: lowercase : List[str] =None lowercase : int =LmSeqsDataset(params=__magic_name__ , data=__magic_name__ ) logger.info('''Data loader created.''' ) # STUDENT # logger.info(f'''Loading student config from {args.student_config}''' ) lowercase : Optional[int] =student_config_class.from_pretrained(args.student_config ) lowercase : List[Any] =True if args.student_pretrained_weights is not None: logger.info(f'''Loading pretrained weights from {args.student_pretrained_weights}''' ) lowercase : Optional[int] =student_model_class.from_pretrained(args.student_pretrained_weights , config=__magic_name__ ) else: lowercase : int =student_model_class(__magic_name__ ) if args.n_gpu > 0: student.to(f'''cuda:{args.local_rank}''' ) logger.info('''Student loaded.''' ) # TEACHER # lowercase : List[Any] =teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__magic_name__ ) if args.n_gpu > 0: teacher.to(f'''cuda:{args.local_rank}''' ) logger.info(f'''Teacher loaded from {args.teacher_name}.''' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__magic_name__ , __magic_name__ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__magic_name__ , __magic_name__ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() lowercase : Optional[Any] =Distiller( params=__magic_name__ , dataset=__magic_name__ , token_probs=__magic_name__ , student=__magic_name__ , teacher=__magic_name__ ) distiller.train() logger.info('''Let\'s go get some drinks.''' ) if __name__ == "__main__": main()
92
'''simple docstring''' import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser UpperCamelCase_ = logging.getLogger(__name__) torch.set_grad_enabled(False) UpperCamelCase_ = """cuda""" if torch.cuda.is_available() else """cpu""" def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : Tuple=100 , __magic_name__ : Optional[int]=" " ) -> List[str]: lowercase : List[Any] =text.split(__magic_name__ ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(__magic_name__ ) , __magic_name__ )] def _lowerCAmelCase ( __magic_name__ : dict ) -> dict: lowercase , lowercase : int =[], [] for title, text in zip(documents['''title'''] , documents['''text'''] ): if text is not None: for passage in split_text(__magic_name__ ): titles.append(title if title is not None else '''''' ) texts.append(__magic_name__ ) return {"title": titles, "text": texts} def _lowerCAmelCase ( __magic_name__ : dict , __magic_name__ : DPRContextEncoder , __magic_name__ : DPRContextEncoderTokenizerFast ) -> dict: lowercase : Dict =ctx_tokenizer( documents['''title'''] , documents['''text'''] , truncation=__magic_name__ , padding='''longest''' , return_tensors='''pt''' )['''input_ids'''] lowercase : Optional[int] =ctx_encoder(input_ids.to(device=__magic_name__ ) , return_dict=__magic_name__ ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def _lowerCAmelCase ( __magic_name__ : "RagExampleArguments" , __magic_name__ : "ProcessingArguments" , __magic_name__ : "IndexHnswArguments" , ) -> str: ###################################### logger.info('''Step 1 - Create the dataset''' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way lowercase : Tuple =load_dataset( '''csv''' , data_files=[rag_example_args.csv_path] , split='''train''' , delimiter='''\t''' , column_names=['''title''', '''text'''] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words lowercase : Optional[int] =dataset.map(__magic_name__ , batched=__magic_name__ , num_proc=processing_args.num_proc ) # And compute the embeddings lowercase : Any =DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=__magic_name__ ) lowercase : Any =DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) lowercase : Optional[int] =Features( {'''text''': Value('''string''' ), '''title''': Value('''string''' ), '''embeddings''': Sequence(Value('''float32''' ) )} ) # optional, save as float32 instead of float64 to save space lowercase : Optional[Any] =dataset.map( partial(__magic_name__ , ctx_encoder=__magic_name__ , ctx_tokenizer=__magic_name__ ) , batched=__magic_name__ , batch_size=processing_args.batch_size , features=__magic_name__ , ) # And finally save your dataset lowercase : Optional[Any] =os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset''' ) dataset.save_to_disk(__magic_name__ ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('''Step 2 - Index the dataset''' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search lowercase : Union[str, Any] =faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('''embeddings''' , custom_index=__magic_name__ ) # And save the index lowercase : Dict =os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset_hnsw_index.faiss''' ) dataset.get_index('''embeddings''' ).save(__magic_name__ ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field( default=str(Path(lowercase__ ).parent / 'test_run' / 'dummy-kb' / 'my_knowledge_dataset.csv' ) , metadata={'help': 'Path to a tab-separated csv file with columns \'title\' and \'text\''} , ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'} , ) lowerCamelCase_ = field( default='facebook/rag-sequence-nq' , metadata={'help': 'The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''} , ) lowerCamelCase_ = field( default='facebook/dpr-ctx_encoder-multiset-base' , metadata={ 'help': ( 'The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or' ' \'facebook/dpr-ctx_encoder-multiset-base\'' ) } , ) lowerCamelCase_ = field( default=str(Path(lowercase__ ).parent / 'test_run' / 'dummy-kb' ) , metadata={'help': 'Path to a directory where the dataset passages and the index will be saved'} , ) @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field( default=lowercase__ , metadata={ 'help': 'The number of processes to use to split the documents into passages. Default is single process.' } , ) lowerCamelCase_ = field( default=16 , metadata={ 'help': 'The batch size to use when computing the passages embeddings using the DPR context encoder.' } , ) @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field( default=7_68 , metadata={'help': 'The dimension of the embeddings to pass to the HNSW Faiss index.'} , ) lowerCamelCase_ = field( default=1_28 , metadata={ 'help': ( 'The number of bi-directional links created for every new element during the HNSW index construction.' ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) UpperCamelCase_ = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: UpperCamelCase_ = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
92
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.linear_k""": """encoder.layers.*.self_attn.linear_k""", """self_attn.linear_v""": """encoder.layers.*.self_attn.linear_v""", """self_attn.linear_q""": """encoder.layers.*.self_attn.linear_q""", """self_attn.pos_bias_u""": """encoder.layers.*.self_attn.pos_bias_u""", """self_attn.pos_bias_v""": """encoder.layers.*.self_attn.pos_bias_v""", """self_attn.linear_out""": """encoder.layers.*.self_attn.linear_out""", """self_attn.linear_pos""": """encoder.layers.*.self_attn.linear_pos""", """self_attn.rotary_emb""": """encoder.embed_positions""", """self_attn_layer_norm""": """encoder.layers.*.self_attn_layer_norm""", """conv_module.pointwise_conv1""": """encoder.layers.*.conv_module.pointwise_conv1""", """conv_module.pointwise_conv2""": """encoder.layers.*.conv_module.pointwise_conv2""", """conv_module.depthwise_conv""": """encoder.layers.*.conv_module.depthwise_conv""", """conv_module.batch_norm""": """encoder.layers.*.conv_module.batch_norm""", """conv_module.layer_norm""": """encoder.layers.*.conv_module.layer_norm""", """ffn1.w_1""": """encoder.layers.*.ffn1.intermediate_dense""", """ffn1.w_2""": """encoder.layers.*.ffn1.output_dense""", """ffn1.layer_norm""": """encoder.layers.*.ffn1_layer_norm""", """ffn2.w_1""": """encoder.layers.*.ffn2.intermediate_dense""", """ffn2.w_2""": """encoder.layers.*.ffn2.output_dense""", """ffn2.layer_norm""": """encoder.layers.*.ffn2_layer_norm""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } UpperCamelCase_ = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def _lowerCAmelCase ( __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ) -> str: for attribute in key.split('''.''' ): lowercase : Tuple =getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: lowercase : Optional[int] =getattr(__magic_name__ , __magic_name__ ).shape else: lowercase : List[Any] =hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": lowercase : Any =value elif weight_type == "weight_g": lowercase : List[Any] =value elif weight_type == "weight_v": lowercase : Union[str, Any] =value elif weight_type == "bias": lowercase : Tuple =value elif weight_type == "running_mean": lowercase : Union[str, Any] =value elif weight_type == "running_var": lowercase : str =value elif weight_type == "num_batches_tracked": lowercase : Tuple =value elif weight_type == "inv_freq": lowercase : Optional[Any] =value else: lowercase : Tuple =value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Union[str, Any]: lowercase : Optional[int] =[] lowercase : Tuple =fairseq_model.state_dict() lowercase : List[Any] =hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): lowercase : Tuple =False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == '''group''' , ) lowercase : List[Any] =True else: for key, mapped_key in MAPPING.items(): lowercase : Optional[int] ='''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: lowercase : Union[str, Any] =True if "*" in mapped_key: lowercase : Optional[int] =name.split(__magic_name__ )[0].split('''.''' )[-2] lowercase : List[str] =mapped_key.replace('''*''' , __magic_name__ ) if "pos_bias_u" in name: lowercase : Optional[Any] =None elif "pos_bias_v" in name: lowercase : Union[str, Any] =None elif "weight_g" in name: lowercase : Any ='''weight_g''' elif "weight_v" in name: lowercase : Tuple ='''weight_v''' elif "bias" in name: lowercase : Optional[int] ='''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj lowercase : Optional[int] ='''weight''' elif "running_mean" in name: lowercase : Union[str, Any] ='''running_mean''' elif "inv_freq" in name: lowercase : Any ='''inv_freq''' elif "running_var" in name: lowercase : Tuple ='''running_var''' elif "num_batches_tracked" in name: lowercase : Dict ='''num_batches_tracked''' else: lowercase : str =None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple ) -> int: lowercase : Optional[Any] =full_name.split('''conv_layers.''' )[-1] lowercase : Any =name.split('''.''' ) lowercase : List[str] =int(items[0] ) lowercase : Union[str, Any] =int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) lowercase : Union[str, Any] =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) lowercase : Optional[Any] =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) lowercase : Optional[int] =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) lowercase : str =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def _lowerCAmelCase ( __magic_name__ : List[str] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=None , __magic_name__ : Union[str, Any]=True ) -> Union[str, Any]: if config_path is not None: lowercase : Optional[Any] =WavaVecaConformerConfig.from_pretrained(__magic_name__ , hidden_act='''swish''' ) else: lowercase : Optional[int] =WavaVecaConformerConfig() if "rope" in checkpoint_path: lowercase : Dict ='''rotary''' if is_finetuned: if dict_path: lowercase : Optional[Any] =Dictionary.load(__magic_name__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowercase : str =target_dict.pad_index lowercase : Union[str, Any] =target_dict.bos_index lowercase : Any =target_dict.eos_index lowercase : Tuple =len(target_dict.symbols ) lowercase : str =os.path.join(__magic_name__ , '''vocab.json''' ) if not os.path.isdir(__magic_name__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__magic_name__ ) ) return os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) lowercase : Dict =target_dict.indices # fairseq has the <pad> and <s> switched lowercase : str =0 lowercase : List[Any] =1 with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(__magic_name__ , __magic_name__ ) lowercase : List[str] =WavaVecaCTCTokenizer( __magic_name__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=__magic_name__ , ) lowercase : Optional[int] =True if config.feat_extract_norm == '''layer''' else False lowercase : str =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__magic_name__ , return_attention_mask=__magic_name__ , ) lowercase : Tuple =WavaVecaProcessor(feature_extractor=__magic_name__ , tokenizer=__magic_name__ ) processor.save_pretrained(__magic_name__ ) lowercase : str =WavaVecaConformerForCTC(__magic_name__ ) else: lowercase : Tuple =WavaVecaConformerForPreTraining(__magic_name__ ) if is_finetuned: lowercase , lowercase , lowercase : Optional[int] =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: lowercase : Dict =argparse.Namespace(task='''audio_pretraining''' ) lowercase : Optional[int] =fairseq.tasks.setup_task(__magic_name__ ) lowercase , lowercase , lowercase : str =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__magic_name__ ) lowercase : List[Any] =model[0].eval() recursively_load_weights(__magic_name__ , __magic_name__ , not is_finetuned ) hf_wavavec.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase_ = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
92
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): UpperCamelCase_ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCamelCase_ = 128022 UpperCamelCase_ = 128028 @require_sentencepiece class __SCREAMING_SNAKE_CASE ( lowercase__ , unittest.TestCase ): lowerCamelCase_ = MaMaaaTokenizer lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = True def lowerCamelCase_ ( self : Dict ): '''simple docstring''' super().setUp() lowercase : Dict =['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] lowercase : List[Any] =dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) lowercase : List[Any] =Path(self.tmpdirname ) save_json(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) lowercase : Tuple =MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self : Any , **UpperCAmelCase__ : int ): '''simple docstring''' return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : Dict ): '''simple docstring''' return ( "This is a test", "This is a test", ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' lowercase : Tuple ='''</s>''' lowercase : Union[str, Any] =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase : List[Any] =self.get_tokenizer() lowercase : Optional[Any] =list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<s>''' ) self.assertEqual(len(UpperCAmelCase__ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('''Skip this test while all models are still to be uploaded.''' ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Union[str, Any] =self.get_tokenizer() lowercase : str =tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [2, 3, 4, 5, 6] , ) lowercase : Optional[int] =tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) lowercase : Tuple =tokenizer.convert_tokens_to_string(UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , '''This is a test''' ) @slow def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' # fmt: off lowercase : int ={'''input_ids''': [[128022, 110108, 397, 11, 38272, 2247, 124811, 285, 18105, 1586, 207, 7, 39534, 4428, 397, 1019, 18105, 1586, 207, 7, 41337, 16786, 241, 7, 20214, 17, 125690, 10398, 7, 44378, 58069, 68342, 7798, 7343, 11, 299, 33310, 4, 158, 37350, 94077, 4569, 299, 33310, 90, 4, 52840, 290, 4, 31270, 112, 299, 682, 4, 52840, 39953, 14079, 193, 52519, 90894, 17894, 120697, 11, 40445, 551, 17, 1019, 52519, 90894, 17756, 963, 11, 40445, 480, 17, 9792, 1120, 5173, 1393, 6240, 16786, 241, 120996, 28, 1245, 1393, 118240, 11123, 1019, 93612, 2691, 10618, 98058, 120409, 1928, 279, 4, 40683, 367, 178, 207, 1019, 103, 103121, 506, 65296, 5, 2], [128022, 21217, 367, 117, 125450, 128, 719, 7, 7308, 40, 93612, 12669, 1116, 16704, 71, 17785, 3699, 15592, 35, 144, 9584, 241, 11943, 713, 950, 799, 2247, 88427, 150, 149, 118813, 120706, 1019, 106906, 81518, 28, 1224, 22799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [128022, 1658, 123311, 5155, 5578, 4722, 279, 14947, 2366, 1120, 1197, 14, 1348, 9232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , ) @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): lowerCamelCase_ = 'facebook/m2m100_418M' lowerCamelCase_ = [ 'In my opinion, there are two levels of response from the French government.', 'NSA Affair Emphasizes Complete Lack of Debate on Intelligence', ] lowerCamelCase_ = [ 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.', 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement', ] # fmt: off lowerCamelCase_ = [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2] @classmethod def lowerCamelCase_ ( cls : Optional[Any] ): '''simple docstring''' lowercase : MaMaaaTokenizer =MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' ) lowercase : Optional[int] =1 return cls def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 128006 ) self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 128022 ) self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 128076 ) self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 128063 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : List[str] =self.tokenizer.get_vocab() self.assertEqual(len(UpperCAmelCase__ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['''<unk>'''] , 3 ) self.assertIn(self.tokenizer.get_lang_token('''en''' ) , UpperCAmelCase__ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : List[Any] ='''en''' lowercase : Optional[Any] =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase__ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids ) # fmt: off lowercase : str =[FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 14028, 136, 3286, 9706, 6, 90797, 6, 144012, 162, 88128, 30061, 5, 2] # fmt: on lowercase : Optional[Any] =self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) lowercase : Optional[Any] =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : Any =tempfile.mkdtemp() lowercase : Tuple =self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(UpperCAmelCase__ ) lowercase : Union[str, Any] =MaMaaaTokenizer.from_pretrained(UpperCAmelCase__ ) self.assertDictEqual(new_tok.lang_token_to_id , UpperCAmelCase__ ) @require_torch def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase : List[str] ='''en''' lowercase : int ='''fr''' lowercase : Union[str, Any] =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase__ , return_tensors='''pt''' ) lowercase : str =shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: lowercase : int =batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : Optional[int] ='''mr''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) lowercase : Union[str, Any] ='''zh''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : int ='''mr''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) lowercase : Optional[Any] ='''zh''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def lowerCamelCase_ ( self : Any ): '''simple docstring''' lowercase : Optional[Any] =self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) , { # en_XX, A, test, EOS '''input_ids''': [[128022, 58, 4183, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 128006, } , )
92
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""", } class __SCREAMING_SNAKE_CASE ( lowercase__ ): lowerCamelCase_ = 'luke' def __init__( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=50267 , UpperCAmelCase__ : List[Any]=500000 , UpperCAmelCase__ : Tuple=768 , UpperCAmelCase__ : Dict=256 , UpperCAmelCase__ : List[str]=12 , UpperCAmelCase__ : List[Any]=12 , UpperCAmelCase__ : List[str]=3072 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Tuple=512 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : List[str]=1E-12 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[str]=1 , UpperCAmelCase__ : Dict=0 , UpperCAmelCase__ : List[str]=2 , **UpperCAmelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) lowercase : List[Any] =vocab_size lowercase : Optional[Any] =entity_vocab_size lowercase : Dict =hidden_size lowercase : List[str] =entity_emb_size lowercase : str =num_hidden_layers lowercase : Dict =num_attention_heads lowercase : Any =hidden_act lowercase : str =intermediate_size lowercase : Any =hidden_dropout_prob lowercase : Dict =attention_probs_dropout_prob lowercase : List[str] =max_position_embeddings lowercase : Union[str, Any] =type_vocab_size lowercase : Union[str, Any] =initializer_range lowercase : int =layer_norm_eps lowercase : str =use_entity_aware_attention lowercase : Any =classifier_dropout
92
'''simple docstring''' def _lowerCAmelCase ( __magic_name__ : int = 600851475143 ) -> int: try: lowercase : Any =int(__magic_name__ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) lowercase : Optional[Any] =2 lowercase : Dict =0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 lowercase : Union[str, Any] =i while n % i == 0: lowercase : Optional[int] =n // i i += 1 return int(__magic_name__ ) if __name__ == "__main__": print(f'''{solution() = }''')
92
1
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase_ = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) UpperCamelCase_ = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'''transformer.encoder.layers.{i}.self_attn.out_proj.weight''', f'''encoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (f'''transformer.encoder.layers.{i}.self_attn.out_proj.bias''', f'''encoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.weight''', f'''encoder.layers.{i}.fc1.weight''')) rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.bias''', f'''encoder.layers.{i}.fc1.bias''')) rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.weight''', f'''encoder.layers.{i}.fc2.weight''')) rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.bias''', f'''encoder.layers.{i}.fc2.bias''')) rename_keys.append( (f'''transformer.encoder.layers.{i}.norm1.weight''', f'''encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((f'''transformer.encoder.layers.{i}.norm1.bias''', f'''encoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append((f'''transformer.encoder.layers.{i}.norm2.weight''', f'''encoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((f'''transformer.encoder.layers.{i}.norm2.bias''', f'''encoder.layers.{i}.final_layer_norm.bias''')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', f'''decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (f'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', f'''decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append( ( f'''transformer.decoder.layers.{i}.multihead_attn.out_proj.weight''', f'''decoder.layers.{i}.encoder_attn.out_proj.weight''', ) ) rename_keys.append( ( f'''transformer.decoder.layers.{i}.multihead_attn.out_proj.bias''', f'''decoder.layers.{i}.encoder_attn.out_proj.bias''', ) ) rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.weight''', f'''decoder.layers.{i}.fc1.weight''')) rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.bias''', f'''decoder.layers.{i}.fc1.bias''')) rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.weight''', f'''decoder.layers.{i}.fc2.weight''')) rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.bias''', f'''decoder.layers.{i}.fc2.bias''')) rename_keys.append( (f'''transformer.decoder.layers.{i}.norm1.weight''', f'''decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((f'''transformer.decoder.layers.{i}.norm1.bias''', f'''decoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append( (f'''transformer.decoder.layers.{i}.norm2.weight''', f'''decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append( (f'''transformer.decoder.layers.{i}.norm2.bias''', f'''decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((f'''transformer.decoder.layers.{i}.norm3.weight''', f'''decoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((f'''transformer.decoder.layers.{i}.norm3.bias''', f'''decoder.layers.{i}.final_layer_norm.bias''')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("""input_proj.weight""", """input_projection.weight"""), ("""input_proj.bias""", """input_projection.bias"""), ("""query_embed.weight""", """query_position_embeddings.weight"""), ("""transformer.encoder.norm.weight""", """encoder.layernorm.weight"""), ("""transformer.encoder.norm.bias""", """encoder.layernorm.bias"""), ("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""), ("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""), ("""class_embed.weight""", """class_labels_classifier.weight"""), ("""class_embed.bias""", """class_labels_classifier.bias"""), ("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""), ("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""), ("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""), ("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""), ("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""), ("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""), ] ) def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : Any , __magic_name__ : List[str] ) -> Union[str, Any]: lowercase : Optional[int] =state_dict.pop(__magic_name__ ) lowercase : List[str] =val def _lowerCAmelCase ( __magic_name__ : Optional[int] ) -> Optional[Any]: lowercase : str =OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: lowercase : Optional[Any] =key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) lowercase : Optional[Any] =value else: lowercase : Any =value return new_state_dict def _lowerCAmelCase ( __magic_name__ : int ) -> Dict: lowercase : Tuple ='''''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) lowercase : List[str] =state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) lowercase : List[str] =state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict lowercase : List[str] =in_proj_weight[:256, :] lowercase : str =in_proj_bias[:256] lowercase : Optional[int] =in_proj_weight[256:512, :] lowercase : Optional[int] =in_proj_bias[256:512] lowercase : Optional[Any] =in_proj_weight[-256:, :] lowercase : Dict =in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention lowercase : List[Any] =state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) lowercase : Optional[Any] =state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict lowercase : List[Any] =in_proj_weight[:256, :] lowercase : str =in_proj_bias[:256] lowercase : List[Any] =in_proj_weight[256:512, :] lowercase : int =in_proj_bias[256:512] lowercase : Optional[int] =in_proj_weight[-256:, :] lowercase : Any =in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention lowercase : Any =state_dict.pop( f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) lowercase : Dict =state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict lowercase : List[str] =in_proj_weight_cross_attn[:256, :] lowercase : List[str] =in_proj_bias_cross_attn[:256] lowercase : int =in_proj_weight_cross_attn[256:512, :] lowercase : str =in_proj_bias_cross_attn[256:512] lowercase : Union[str, Any] =in_proj_weight_cross_attn[-256:, :] lowercase : Optional[Any] =in_proj_bias_cross_attn[-256:] def _lowerCAmelCase ( __magic_name__ : Union[str, Any] , __magic_name__ : int ) -> Optional[Any]: lowercase , lowercase : Optional[int] =image.size lowercase : Union[str, Any] =max(__magic_name__ , __magic_name__ ) lowercase : List[str] =800 if '''detection''' in checkpoint_url else 1000 lowercase : List[str] =target_max_size / current_max_size lowercase : List[Any] =image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowerCAmelCase ( __magic_name__ : Optional[int] ) -> Dict: lowercase : Tuple =F.to_tensor(__magic_name__ ) lowercase : int =F.normalize(__magic_name__ , mean=[0.4_8_5, 0.4_5_6, 0.4_0_6] , std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ) return image @torch.no_grad() def _lowerCAmelCase ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Dict ) -> Tuple: logger.info('''Converting model...''' ) # load original state dict lowercase : Any =torch.hub.load_state_dict_from_url(__magic_name__ , map_location='''cpu''' ) # rename keys for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) lowercase : List[Any] =rename_backbone_keys(__magic_name__ ) # query, key and value matrices need special treatment read_in_q_k_v(__magic_name__ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them lowercase : str ='''model.''' for key in state_dict.copy().keys(): if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): lowercase : Optional[int] =state_dict.pop(__magic_name__ ) lowercase : str =val # create HuggingFace model and load state dict lowercase : Optional[Any] =TableTransformerConfig( backbone='''resnet18''' , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: lowercase : Any =15 lowercase : Tuple =2 lowercase : Tuple ={0: '''table''', 1: '''table rotated'''} lowercase : Any =idalabel lowercase : Optional[int] ={v: k for k, v in idalabel.items()} else: lowercase : List[Any] =125 lowercase : Any =6 lowercase : List[str] ={ 0: '''table''', 1: '''table column''', 2: '''table row''', 3: '''table column header''', 4: '''table projected row header''', 5: '''table spanning cell''', } lowercase : int =idalabel lowercase : str ={v: k for k, v in idalabel.items()} lowercase : Tuple =DetrImageProcessor( format='''coco_detection''' , max_size=800 if '''detection''' in checkpoint_url else 1000 ) lowercase : Optional[int] =TableTransformerForObjectDetection(__magic_name__ ) model.load_state_dict(__magic_name__ ) model.eval() # verify our conversion lowercase : Any ='''example_pdf.png''' if '''detection''' in checkpoint_url else '''example_table.png''' lowercase : Optional[Any] =hf_hub_download(repo_id='''nielsr/example-pdf''' , repo_type='''dataset''' , filename=__magic_name__ ) lowercase : Optional[Any] =Image.open(__magic_name__ ).convert('''RGB''' ) lowercase : Tuple =normalize(resize(__magic_name__ , __magic_name__ ) ).unsqueeze(0 ) lowercase : List[str] =model(__magic_name__ ) if "detection" in checkpoint_url: lowercase : Any =(1, 15, 3) lowercase : List[str] =torch.tensor( [[-6.7_8_9_7, -1_6.9_9_8_5, 6.7_9_3_7], [-8.0_1_8_6, -2_2.2_1_9_2, 6.9_6_7_7], [-7.3_1_1_7, -2_1.0_7_0_8, 7.4_0_5_5]] ) lowercase : List[str] =torch.tensor([[0.4_8_6_7, 0.1_7_6_7, 0.6_7_3_2], [0.6_7_1_8, 0.4_4_7_9, 0.3_8_3_0], [0.4_7_1_6, 0.1_7_6_0, 0.6_3_6_4]] ) else: lowercase : Dict =(1, 125, 7) lowercase : Dict =torch.tensor( [[-1_8.1_4_3_0, -8.3_2_1_4, 4.8_2_7_4], [-1_8.4_6_8_5, -7.1_3_6_1, -4.2_6_6_7], [-2_6.3_6_9_3, -9.3_4_2_9, -4.9_9_6_2]] ) lowercase : Any =torch.tensor([[0.4_9_8_3, 0.5_5_9_5, 0.9_4_4_0], [0.4_9_1_6, 0.6_3_1_5, 0.5_9_5_4], [0.6_1_0_8, 0.8_6_3_7, 0.1_1_3_5]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __magic_name__ , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __magic_name__ , atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) model.save_pretrained(__magic_name__ ) image_processor.save_pretrained(__magic_name__ ) if push_to_hub: # Push model to HF hub logger.info('''Pushing model to the hub...''' ) lowercase : Optional[Any] =( '''microsoft/table-transformer-detection''' if '''detection''' in checkpoint_url else '''microsoft/table-transformer-structure-recognition''' ) model.push_to_hub(__magic_name__ ) image_processor.push_to_hub(__magic_name__ ) if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument( """--checkpoint_url""", default="""https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth""", type=str, choices=[ """https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth""", """https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth""", ], help="""URL of the Table Transformer checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) UpperCamelCase_ = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
92
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class __SCREAMING_SNAKE_CASE ( lowercase__ ): lowerCamelCase_ = 'speech_to_text_2' lowerCamelCase_ = ['past_key_values'] lowerCamelCase_ = {'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : int , UpperCAmelCase__ : Dict=10000 , UpperCAmelCase__ : Optional[int]=6 , UpperCAmelCase__ : str=2048 , UpperCAmelCase__ : Optional[Any]=4 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[Any]="relu" , UpperCAmelCase__ : List[str]=256 , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : List[Any]=0.0 , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Optional[Any]=0 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : List[Any]=1024 , **UpperCAmelCase__ : Dict , ): '''simple docstring''' lowercase : List[str] =vocab_size lowercase : Optional[int] =d_model lowercase : Optional[Any] =decoder_ffn_dim lowercase : Any =decoder_layers lowercase : Dict =decoder_attention_heads lowercase : List[Any] =dropout lowercase : List[Any] =attention_dropout lowercase : Any =activation_dropout lowercase : Optional[Any] =activation_function lowercase : Optional[int] =init_std lowercase : Dict =decoder_layerdrop lowercase : Optional[int] =use_cache lowercase : Optional[Any] =decoder_layers lowercase : List[str] =scale_embedding # scale factor will be sqrt(d_model) if True lowercase : str =max_target_positions super().__init__( pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , decoder_start_token_id=UpperCAmelCase__ , **UpperCAmelCase__ , )
92
1
'''simple docstring''' import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""): UpperCamelCase_ = True from torch.cuda.amp import autocast UpperCamelCase_ = logging.getLogger(__name__) @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Whether to log verbose messages or not.'} , ) lowerCamelCase_ = field( default=2.0 , metadata={'help': 'Maximum temperature for gumbel softmax.'} ) lowerCamelCase_ = field( default=0.5 , metadata={'help': 'Minimum temperature for gumbel softmax.'} ) lowerCamelCase_ = field( default=0.9_9_9_9_9_5 , metadata={'help': 'Decay of gumbel temperature during training.'} ) def _lowerCAmelCase ( __magic_name__ : ModelArguments , __magic_name__ : TrainingArguments ) -> str: logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) lowercase : int =logging.WARNING if model_args.verbose_logging: lowercase : List[str] =logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): lowercase : int =logging.INFO logger.setLevel(__magic_name__ ) @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) lowerCamelCase_ = field( default='train' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) lowerCamelCase_ = field( default='validation' , metadata={ 'help': ( 'The name of the validation data set split to use (via the datasets library). Defaults to \'validation\'' ) } , ) lowerCamelCase_ = field( default='file' , metadata={'help': 'Column in the dataset that contains speech file path. Defaults to \'file\''} , ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) lowerCamelCase_ = field( default=1 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) lowerCamelCase_ = field( default=2_0.0 , metadata={'help': 'Filter audio files that are longer than `max_duration_in_seconds` seconds'} ) @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = "longest" lowerCamelCase_ = None lowerCamelCase_ = None def __call__( self : Any , UpperCAmelCase__ : List[Dict[str, Union[List[int], torch.Tensor]]] ): '''simple docstring''' # reformat list to dict and set to pytorch format lowercase : str =self.feature_extractor.pad( UpperCAmelCase__ , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) lowercase : List[str] =self.model._get_feat_extract_output_lengths(batch['''input_values'''].shape[-1] ) lowercase : List[Any] =batch['''input_values'''].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula lowercase : Tuple =self.model._get_feat_extract_output_lengths(batch['''attention_mask'''].sum(-1 ) ).to( torch.long ) lowercase : Tuple =torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch['''input_values'''].device ) # these two operations makes sure that all values # before the output lengths indices are attended to lowercase : str =1 lowercase : Union[str, Any] =attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices lowercase : Optional[int] =_compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=UpperCAmelCase__ , min_masks=2 , ) return batch class __SCREAMING_SNAKE_CASE ( lowercase__ ): def __init__( self : Optional[Any] , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , UpperCAmelCase__ : Dict=1.0 , **UpperCAmelCase__ : str ): '''simple docstring''' super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) lowercase : Any =0 lowercase : List[str] =max_gumbel_temp lowercase : int =min_gumbel_temp lowercase : Any =gumbel_temp_decay def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : nn.Module , UpperCAmelCase__ : Dict[str, Union[torch.Tensor, Any]] ): '''simple docstring''' model.train() lowercase : Optional[int] =self._prepare_inputs(UpperCAmelCase__ ) if self.use_amp: with autocast(): lowercase : Dict =self.compute_loss(UpperCAmelCase__ , UpperCAmelCase__ ) else: lowercase : Any =self.compute_loss(UpperCAmelCase__ , UpperCAmelCase__ ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": lowercase : Tuple =loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowercase : str =loss.sum() / (inputs['''mask_time_indices''']).sum() else: raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' ) if self.args.gradient_accumulation_steps > 1: lowercase : int =loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(UpperCAmelCase__ ).backward() elif self.use_apex: with amp.scale_loss(UpperCAmelCase__ , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(UpperCAmelCase__ ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def _lowerCAmelCase ( ) -> str: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase : List[str] =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowercase , lowercase , lowercase : Optional[int] =parser.parse_args_into_dataclasses() configure_logger(__magic_name__ , __magic_name__ ) # Downloading and loading a dataset from the hub. lowercase : Union[str, Any] =load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" lowercase : int =DatasetDict() lowercase : Union[str, Any] =load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'''{data_args.train_split_name}[:{data_args.validation_split_percentage}%]''' , cache_dir=model_args.cache_dir , ) lowercase : Optional[int] =load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'''{data_args.train_split_name}[{data_args.validation_split_percentage}%:]''' , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" lowercase : Any =DatasetDict() lowercase : int =load_dataset( data_args.dataset_name , data_args.dataset_config_name , split='''validation''' , cache_dir=model_args.cache_dir , ) lowercase : Optional[int] =load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'''{data_args.train_split_name}''' , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported lowercase : List[Any] =WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=__magic_name__ ) def prepare_dataset(__magic_name__ : Optional[Any] ): # check that all files have the correct sampling rate lowercase , lowercase : Optional[Any] =librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays lowercase : Optional[Any] =datasets.map( __magic_name__ , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets['''train'''].column_names ) # filter audio files that are too long lowercase : int =vectorized_datasets.filter( lambda __magic_name__ : len(data['''speech'''] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(__magic_name__ : Tuple ): return feature_extractor(batch['''speech'''] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` lowercase : Optional[Any] =vectorized_datasets.map( __magic_name__ , batched=__magic_name__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets['''train'''].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 lowercase : str =WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( '''PreTraining is only supported for ``config.do_stable_layer_norm=True`` and''' ''' ``config.feat_extract_norm=\'layer\'''' ) lowercase : Tuple =WavaVecaForPreTraining(__magic_name__ ) lowercase : Tuple =DataCollatorForWavaVecaPretraining(model=__magic_name__ , feature_extractor=__magic_name__ ) lowercase : Tuple =WavaVecaPreTrainer( model=__magic_name__ , data_collator=__magic_name__ , args=__magic_name__ , train_dataset=vectorized_datasets['''train'''] , eval_dataset=vectorized_datasets['''validation'''] , tokenizer=__magic_name__ , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
92
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __SCREAMING_SNAKE_CASE : def __init__( self : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str]=13 , UpperCAmelCase__ : Any=32 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : List[str]=[10, 20, 30, 40] , UpperCAmelCase__ : Any=[2, 2, 3, 2] , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[Any]=10 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Optional[int]=["stage2", "stage3", "stage4"] , UpperCAmelCase__ : Dict=[2, 3, 4] , UpperCAmelCase__ : Optional[int]=None , ): '''simple docstring''' lowercase : List[Any] =parent lowercase : Tuple =batch_size lowercase : List[str] =image_size lowercase : List[Any] =num_channels lowercase : Union[str, Any] =num_stages lowercase : int =hidden_sizes lowercase : Any =depths lowercase : Tuple =is_training lowercase : str =use_labels lowercase : List[Any] =intermediate_size lowercase : int =hidden_act lowercase : Union[str, Any] =num_labels lowercase : Optional[int] =initializer_range lowercase : int =out_features lowercase : List[str] =out_indices lowercase : str =scope def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : str =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase : Dict =None if self.use_labels: lowercase : List[Any] =ids_tensor([self.batch_size] , self.num_labels ) lowercase : Dict =self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self : Any ): '''simple docstring''' return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] ): '''simple docstring''' lowercase : Dict =ConvNextVaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : Optional[Any] =model(UpperCAmelCase__ ) # 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 lowerCamelCase_ ( self : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ): '''simple docstring''' lowercase : Dict =ConvNextVaForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : str =model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ): '''simple docstring''' lowercase : Union[str, Any] =ConvNextVaBackbone(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : Optional[int] =model(UpperCAmelCase__ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None lowercase : Optional[Any] =None lowercase : str =ConvNextVaBackbone(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : Optional[Any] =model(UpperCAmelCase__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Any =self.prepare_config_and_inputs() lowercase , lowercase , lowercase : str =config_and_inputs lowercase : Any ={'''pixel_values''': pixel_values} return config, inputs_dict def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : str =self.prepare_config_and_inputs() lowercase , lowercase , lowercase : List[str] =config_and_inputs lowercase : Optional[Any] ={'''pixel_values''': pixel_values, '''labels''': labels} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ): lowerCamelCase_ = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCamelCase_ = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' lowercase : Dict =ConvNextVaModelTester(self ) lowercase : str =ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCamelCase_ ( self : Any ): '''simple docstring''' return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' pass def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: lowercase , lowercase : Union[str, Any] =self.model_tester.prepare_config_and_inputs_with_labels() lowercase : Optional[int] =True if model_class.__name__ in [ *get_values(UpperCAmelCase__ ), *get_values(UpperCAmelCase__ ), ]: continue lowercase : Dict =model_class(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.train() lowercase : Optional[Any] =self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) lowercase : List[Any] =model(**UpperCAmelCase__ ).loss loss.backward() def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: lowercase , lowercase : Any =self.model_tester.prepare_config_and_inputs_with_labels() lowercase : List[Any] =False lowercase : Any =True if ( model_class.__name__ in [*get_values(UpperCAmelCase__ ), *get_values(UpperCAmelCase__ )] or not model_class.supports_gradient_checkpointing ): continue lowercase : Any =model_class(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.gradient_checkpointing_enable() model.train() lowercase : Optional[Any] =self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) lowercase : int =model(**UpperCAmelCase__ ).loss loss.backward() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase , lowercase : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : Dict =model_class(UpperCAmelCase__ ) lowercase : Union[str, Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase : int =[*signature.parameters.keys()] lowercase : Optional[Any] =['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' lowercase : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' def check_hidden_states_output(UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple ): lowercase : int =model_class(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() with torch.no_grad(): lowercase : Any =model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) lowercase : Dict =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowercase : List[Any] =self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase__ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowercase , lowercase : List[str] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : List[str] =True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase : Tuple =True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' lowercase : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) @slow def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : List[Any] =ConvNextVaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def _lowerCAmelCase ( ) -> List[Any]: lowercase : Union[str, Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' lowercase : Tuple =ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(UpperCAmelCase__ ) lowercase : int =self.default_image_processor lowercase : List[str] =prepare_img() lowercase : List[Any] =preprocessor(images=UpperCAmelCase__ , return_tensors='''pt''' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): lowercase : Dict =model(**UpperCAmelCase__ ) # verify the logits lowercase : Optional[Any] =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) lowercase : Tuple =torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) )
92
1