code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : str ): lowerCamelCase_ = len(__lowerCamelCase ) lowerCamelCase_ = [] for i in range(len(__lowerCamelCase ) - pat_len + 1 ): lowerCamelCase_ = True for j in range(__lowerCamelCase ): if s[i + j] != pattern[j]: lowerCamelCase_ = False break if match_found: position.append(__lowerCamelCase ) return position if __name__ == "__main__": assert naive_pattern_search("""ABCDEFG""", """DE""") == [3] print(naive_pattern_search("""ABAAABCDBBABCDDEBCABC""", """ABC"""))
55
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def _UpperCAmelCase ( __lowerCamelCase : Tuple ) -> Optional[int]: _snake_case = checkpoints.load_tax_checkpoint(__lowerCamelCase ) _snake_case = flatten_dict(__lowerCamelCase ) return flax_params def _UpperCAmelCase ( __lowerCamelCase : Dict ) -> Optional[int]: _snake_case = {} _snake_case = { '''token_embedder''': '''embeddings''', '''encoder_norm''': '''layernorm''', '''kernel''': '''weight''', '''.out''': '''.output''', '''scale''': '''weight''', '''embedders_0.pos_embedding''': '''row_embedder.weight''', '''embedders_1.pos_embedding''': '''column_embedder.weight''', } _snake_case = { '''query''': '''attention.query''', '''key''': '''attention.key''', '''value''': '''attention.value''', '''output.dense''': '''output''', '''encoder_decoder_attention.o''': '''encoder_decoder_attention.attention.o''', '''pre_self_attention_layer_norm''': '''self_attention.layer_norm''', '''pre_cross_attention_layer_norm''': '''encoder_decoder_attention.layer_norm''', '''mlp.''': '''mlp.DenseReluDense.''', '''pre_mlp_layer_norm''': '''mlp.layer_norm''', '''self_attention.o''': '''self_attention.attention.o''', '''decoder.embeddings.embedding''': '''decoder.embed_tokens.weight''', '''decoder.relpos_bias.rel_embedding''': '''decoder.layer.0.self_attention.attention.relative_attention_bias.weight''', '''decoder.decoder_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.logits_dense.weight''': '''decoder.lm_head.weight''', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key _snake_case = '''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): _snake_case = new_key.replace(__lowerCamelCase , __lowerCamelCase ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): _snake_case = new_key.replace(__lowerCamelCase , __lowerCamelCase ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number _snake_case = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __lowerCamelCase ) _snake_case = new_key.replace('''encoder''' , '''encoder.encoder''' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number _snake_case = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __lowerCamelCase ) _snake_case = flax_dict[key] _snake_case = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): _snake_case = torch.from_numpy(converted_dict[key].T ) else: _snake_case = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def _UpperCAmelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : Any=False , __lowerCamelCase : Optional[int]=False ) -> int: _snake_case = get_flax_param(__lowerCamelCase ) if not use_large: _snake_case = PixaStructVisionConfig() _snake_case = PixaStructTextConfig() else: _snake_case = PixaStructVisionConfig( hidden_size=15_36 , d_ff=39_68 , num_attention_heads=24 , num_hidden_layers=18 ) _snake_case = PixaStructTextConfig(hidden_size=15_36 , d_ff=39_68 , num_heads=24 , num_layers=18 ) _snake_case = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__lowerCamelCase ) _snake_case = PixaStructForConditionalGeneration(__lowerCamelCase ) _snake_case = rename_and_convert_flax_params(__lowerCamelCase ) model.load_state_dict(__lowerCamelCase ) _snake_case = AutoTokenizer.from_pretrained('''ybelkada/test-pix2struct-tokenizer''' ) _snake_case = PixaStructImageProcessor() _snake_case = PixaStructProcessor(image_processor=__lowerCamelCase , tokenizer=__lowerCamelCase ) if use_large: _snake_case = 40_96 _snake_case = True # mkdir if needed os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) model.save_pretrained(__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) print('''Model saved in {}'''.format(__lowerCamelCase ) ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument('--t5x_checkpoint_path', default=None, type=str, help='Path to the original T5x checkpoint.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--use_large', action='store_true', help='Use large model.') parser.add_argument('--is_vqa', action='store_true', help='Use large model.') UpperCAmelCase__ = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
288
0
'''simple docstring''' class UpperCAmelCase_ : """simple docstring""" def __init__( self : List[str] ): snake_case__ : List[str] = """""" snake_case__ : List[str] = """""" snake_case__ : Any = [] def lowerCamelCase ( self : Any , snake_case_ : int , snake_case_ : int ): 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]: snake_case__ : List[str] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: snake_case__ : Tuple = self.__min_dist_top_down_dp(snake_case_ , n - 1 ) snake_case__ : Any = self.__min_dist_top_down_dp(m - 1 , snake_case_ ) snake_case__ : str = self.__min_dist_top_down_dp(m - 1 , n - 1 ) snake_case__ : str = 1 + min(snake_case_ , snake_case_ , snake_case_ ) return self.dp[m][n] def lowerCamelCase ( self : Dict , snake_case_ : str , snake_case_ : str ): snake_case__ : Any = worda snake_case__ : Union[str, Any] = worda snake_case__ : Tuple = [[-1 for _ in range(len(snake_case_ ) )] for _ in range(len(snake_case_ ) )] return self.__min_dist_top_down_dp(len(snake_case_ ) - 1 , len(snake_case_ ) - 1 ) def lowerCamelCase ( self : Any , snake_case_ : str , snake_case_ : str ): snake_case__ : List[str] = worda snake_case__ : Optional[Any] = worda snake_case__ : List[str] = len(snake_case_ ) snake_case__ : Optional[int] = len(snake_case_ ) snake_case__ : Tuple = [[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 snake_case__ : Union[str, Any] = j elif j == 0: # second string is empty snake_case__ : Dict = i elif worda[i - 1] == worda[j - 1]: # last characters are equal snake_case__ : List[Any] = self.dp[i - 1][j - 1] else: snake_case__ : Optional[Any] = self.dp[i][j - 1] snake_case__ : Any = self.dp[i - 1][j] snake_case__ : int = self.dp[i - 1][j - 1] snake_case__ : int = 1 + min(snake_case_ , snake_case_ , snake_case_ ) return self.dp[m][n] if __name__ == "__main__": __a = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() __a = input("Enter the first string: ").strip() __a = 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 ***************")
352
'''simple docstring''' def __snake_case( _lowerCAmelCase ) -> int: if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError("""Input value must be an 'int' type""" ) snake_case__ : List[str] = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
43
0
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=9_9 , lowerCAmelCase__=3_2 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=3_7 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_6 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__="None" , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , ): __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = relative_attention __SCREAMING_SNAKE_CASE = position_biased_input __SCREAMING_SNAKE_CASE = pos_att_type __SCREAMING_SNAKE_CASE = scope def snake_case_ ( self): __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case_ ( self): return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.get_config() __SCREAMING_SNAKE_CASE = 3_0_0 return config def snake_case_ ( self , lowerCAmelCase__): self.parent.assertListEqual(list(result.loss.size()) , []) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = DebertaModel(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__)[0] __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , token_type_ids=lowerCAmelCase__)[0] __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__)[0] self.parent.assertListEqual(list(sequence_output.size()) , [self.batch_size, self.seq_length, self.hidden_size]) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = DebertaForMaskedLM(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DebertaForSequenceClassification(lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__) self.parent.assertListEqual(list(result.logits.size()) , [self.batch_size, self.num_labels]) self.check_loss_output(lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DebertaForTokenClassification(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = DebertaForQuestionAnswering(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_SNAKE_CASE = model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , start_positions=lowerCAmelCase__ , end_positions=lowerCAmelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( __a , __a , unittest.TestCase ): """simple docstring""" __lowercase : Dict = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) __lowercase : Any = ( { '''feature-extraction''': DebertaModel, '''fill-mask''': DebertaForMaskedLM, '''question-answering''': DebertaForQuestionAnswering, '''text-classification''': DebertaForSequenceClassification, '''token-classification''': DebertaForTokenClassification, '''zero-shot''': DebertaForSequenceClassification, } if is_torch_available() else {} ) __lowercase : int = True __lowercase : Optional[int] = False __lowercase : str = False __lowercase : Tuple = False __lowercase : Optional[int] = False def snake_case_ ( self): __SCREAMING_SNAKE_CASE = DebertaModelTester(self) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=lowerCAmelCase__ , hidden_size=3_7) def snake_case_ ( self): self.config_tester.run_common_tests() def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*lowerCAmelCase__) @slow def snake_case_ ( self): for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = DebertaModel.from_pretrained(lowerCAmelCase__) self.assertIsNotNone(lowerCAmelCase__) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason="""Model not available yet""") def snake_case_ ( self): pass @slow def snake_case_ ( self): __SCREAMING_SNAKE_CASE = DebertaModel.from_pretrained("""microsoft/deberta-base""") __SCREAMING_SNAKE_CASE = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]]) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__)[0] # compare the actual values for a slice. __SCREAMING_SNAKE_CASE = torch.tensor( [[[-0.59_86, -0.80_55, -0.84_62], [1.44_84, -0.93_48, -0.80_59], [0.31_23, 0.00_32, -1.41_31]]]) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCAmelCase__ , atol=1E-4) , f"{output[:, 1:4, 1:4]}")
100
"""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 SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" __lowercase : List[Any] = ['''image_processor''', '''tokenizer'''] __lowercase : List[Any] = '''BridgeTowerImageProcessor''' __lowercase : Tuple = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , lowerCAmelCase__ , lowerCAmelCase__): super().__init__(lowerCAmelCase__ , lowerCAmelCase__) def __call__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = True , lowerCAmelCase__ = None , **lowerCAmelCase__ , ): __SCREAMING_SNAKE_CASE = self.tokenizer( text=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , stride=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , return_overflowing_tokens=lowerCAmelCase__ , return_special_tokens_mask=lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , return_length=lowerCAmelCase__ , verbose=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ , ) # add pixel_values + pixel_mask __SCREAMING_SNAKE_CASE = self.image_processor( lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , do_normalize=lowerCAmelCase__ , do_center_crop=lowerCAmelCase__ , **lowerCAmelCase__) encoding.update(lowerCAmelCase__) return encoding def snake_case_ ( self , *lowerCAmelCase__ , **lowerCAmelCase__): return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__) def snake_case_ ( self , *lowerCAmelCase__ , **lowerCAmelCase__): return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__) @property def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names __SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
100
1
"""simple docstring""" def __lowerCAmelCase ( lowercase : str ) -> bool: """simple docstring""" if not all(x.isalpha() for x in string ): raise ValueError("String must only contain alphabetic characters." ) snake_case : Any = sorted(string.lower() ) return len(lowercase ) == len(set(lowercase ) ) if __name__ == "__main__": __snake_case = input("""Enter a string """).strip() __snake_case = is_isogram(input_str) print(F'''{input_str} is {"an" if isogram else "not an"} isogram.''')
112
"""simple docstring""" def __lowerCAmelCase ( lowercase : int ) -> int: """simple docstring""" if not isinstance(lowercase , lowercase ): raise ValueError("Input must be an integer" ) if input_num <= 0: raise ValueError("Input must be positive" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
112
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available A__ : List[Any] ={ '''configuration_gpt_neo''': ['''GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoConfig''', '''GPTNeoOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[str] =[ '''GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoForCausalLM''', '''GPTNeoForQuestionAnswering''', '''GPTNeoForSequenceClassification''', '''GPTNeoForTokenClassification''', '''GPTNeoModel''', '''GPTNeoPreTrainedModel''', '''load_tf_weights_in_gpt_neo''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict =[ '''FlaxGPTNeoForCausalLM''', '''FlaxGPTNeoModel''', '''FlaxGPTNeoPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys A__ : int =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCamelCase_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt") UpperCamelCase_ = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) UpperCamelCase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def lowercase__( __UpperCamelCase: str ): """simple docstring""" with open(__UpperCamelCase ,'rb' ) as f: SCREAMING_SNAKE_CASE : List[str] = Image.open(__UpperCamelCase ) return im.convert('RGB' ) @dataclass class _a : '''simple docstring''' A : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={ '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).''' } , ) A : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) A : Optional[str] = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''A folder containing the training data.'''} ) A : Optional[str] = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''A folder containing the validation data.'''} ) A : Optional[float] = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) A : Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) A : Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def UpperCamelCase_ ( self ): '''simple docstring''' if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( 'You must specify either a dataset name from the hub or a train and/or validation directory.' ) @dataclass class _a : '''simple docstring''' A : str = field( default='''google/vit-base-patch16-224-in21k''' , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} , ) A : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(SCREAMING_SNAKE_CASE )} , ) A : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) A : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) A : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) A : str = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Name or path of preprocessor config.'''} ) A : bool = field( default=SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) A : bool = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''} , ) def lowercase__( __UpperCamelCase: Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = torch.stack([example['pixel_values'] for example in examples] ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([example['labels'] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def lowercase__( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_image_classification' ,__UpperCamelCase ,__UpperCamelCase ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' ,datefmt='%m/%d/%Y %H:%M:%S' ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE : str = training_args.get_process_log_level() logger.setLevel(__UpperCamelCase ) transformers.utils.logging.set_verbosity(__UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE : Optional[int] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE : Union[str, Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Initialize our dataset and prepare it for the 'image-classification' task. if data_args.dataset_name is not None: SCREAMING_SNAKE_CASE : Any = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,cache_dir=model_args.cache_dir ,task='image-classification' ,use_auth_token=True if model_args.use_auth_token else None ,) else: SCREAMING_SNAKE_CASE : Union[str, Any] = {} if data_args.train_dir is not None: SCREAMING_SNAKE_CASE : Tuple = os.path.join(data_args.train_dir ,'**' ) if data_args.validation_dir is not None: SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(data_args.validation_dir ,'**' ) SCREAMING_SNAKE_CASE : str = load_dataset( 'imagefolder' ,data_files=__UpperCamelCase ,cache_dir=model_args.cache_dir ,task='image-classification' ,) # If we don't have a validation split, split off a percentage of train as validation. SCREAMING_SNAKE_CASE : Tuple = None if 'validation' in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split ,__UpperCamelCase ) and data_args.train_val_split > 0.0: SCREAMING_SNAKE_CASE : int = dataset['train'].train_test_split(data_args.train_val_split ) SCREAMING_SNAKE_CASE : Optional[int] = split['train'] SCREAMING_SNAKE_CASE : int = split['test'] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. SCREAMING_SNAKE_CASE : int = dataset['train'].features['labels'].names SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = {}, {} for i, label in enumerate(__UpperCamelCase ): SCREAMING_SNAKE_CASE : List[Any] = str(__UpperCamelCase ) SCREAMING_SNAKE_CASE : int = label # Load the accuracy metric from the datasets package SCREAMING_SNAKE_CASE : Any = evaluate.load('accuracy' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__UpperCamelCase: Dict ): return metric.compute(predictions=np.argmax(p.predictions ,axis=1 ) ,references=p.label_ids ) SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path ,num_labels=len(__UpperCamelCase ) ,labelaid=__UpperCamelCase ,idalabel=__UpperCamelCase ,finetuning_task='image-classification' ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool('.ckpt' in model_args.model_name_or_path ) ,config=__UpperCamelCase ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained( model_args.image_processor_name or model_args.model_name_or_path ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # Define torchvision transforms to be applied to each image. if "shortest_edge" in image_processor.size: SCREAMING_SNAKE_CASE : Optional[Any] = image_processor.size['shortest_edge'] else: SCREAMING_SNAKE_CASE : List[Any] = (image_processor.size['height'], image_processor.size['width']) SCREAMING_SNAKE_CASE : Dict = Normalize(mean=image_processor.image_mean ,std=image_processor.image_std ) SCREAMING_SNAKE_CASE : Dict = Compose( [ RandomResizedCrop(__UpperCamelCase ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) SCREAMING_SNAKE_CASE : List[Any] = Compose( [ Resize(__UpperCamelCase ), CenterCrop(__UpperCamelCase ), ToTensor(), normalize, ] ) def train_transforms(__UpperCamelCase: List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = [ _train_transforms(pil_img.convert('RGB' ) ) for pil_img in example_batch['image'] ] return example_batch def val_transforms(__UpperCamelCase: Dict ): SCREAMING_SNAKE_CASE : List[str] = [_val_transforms(pil_img.convert('RGB' ) ) for pil_img in example_batch['image']] return example_batch if training_args.do_train: if "train" not in dataset: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE : Tuple = ( dataset['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(__UpperCamelCase ) if training_args.do_eval: if "validation" not in dataset: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE : Optional[int] = ( dataset['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(__UpperCamelCase ) # Initalize our trainer SCREAMING_SNAKE_CASE : List[Any] = Trainer( model=__UpperCamelCase ,args=__UpperCamelCase ,train_dataset=dataset['train'] if training_args.do_train else None ,eval_dataset=dataset['validation'] if training_args.do_eval else None ,compute_metrics=__UpperCamelCase ,tokenizer=__UpperCamelCase ,data_collator=__UpperCamelCase ,) # Training if training_args.do_train: SCREAMING_SNAKE_CASE : Any = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE : Any = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE : Optional[Any] = last_checkpoint SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.train(resume_from_checkpoint=__UpperCamelCase ) trainer.save_model() trainer.log_metrics('train' ,train_result.metrics ) trainer.save_metrics('train' ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.evaluate() trainer.log_metrics('eval' ,__UpperCamelCase ) trainer.save_metrics('eval' ,__UpperCamelCase ) # Write model card and (optionally) push to hub SCREAMING_SNAKE_CASE : List[str] = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'image-classification', 'dataset': data_args.dataset_name, 'tags': ['image-classification', 'vision'], } if training_args.push_to_hub: trainer.push_to_hub(**__UpperCamelCase ) else: trainer.create_model_card(**__UpperCamelCase ) if __name__ == "__main__": main()
251
0
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase , unittest.TestCase ): A : Any = RoCBertTokenizer A : str = None A : Union[str, Any] = False A : int = True A : str = filter_non_english def snake_case__ ( self : Tuple ): super().setUp() __snake_case : Any = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] __snake_case : List[Any] = {} __snake_case : List[Any] = {} for i, value in enumerate(_lowerCAmelCase ): __snake_case : Optional[Any] = i __snake_case : int = i __snake_case : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __snake_case : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) __snake_case : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(_lowerCAmelCase , _lowerCAmelCase , ensure_ascii=_lowerCAmelCase ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(_lowerCAmelCase , _lowerCAmelCase , ensure_ascii=_lowerCAmelCase ) def snake_case__ ( self : Union[str, Any] ): __snake_case : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __snake_case : List[Any] = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(_lowerCAmelCase , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(_lowerCAmelCase ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(_lowerCAmelCase ) , [5, 6, 2, 5, 7, 8] ) def snake_case__ ( self : Any ): __snake_case : Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def snake_case__ ( self : Tuple ): __snake_case : Tuple = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def snake_case__ ( self : Tuple ): __snake_case : List[Any] = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def snake_case__ ( self : Tuple ): __snake_case : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def snake_case__ ( self : Dict ): __snake_case : Optional[int] = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def snake_case__ ( self : List[Any] ): __snake_case : str = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def snake_case__ ( self : Any ): __snake_case : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def snake_case__ ( self : str ): __snake_case : Dict = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def snake_case__ ( self : Dict ): __snake_case : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=_lowerCAmelCase , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def snake_case__ ( self : Union[str, Any] ): __snake_case : str = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] __snake_case : int = {} for i, token in enumerate(_lowerCAmelCase ): __snake_case : int = i __snake_case : Union[str, Any] = RoCBertWordpieceTokenizer(vocab=_lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def snake_case__ ( self : List[Any] ): self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def snake_case__ ( self : List[Any] ): self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def snake_case__ ( self : str ): self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def snake_case__ ( self : Union[str, Any] ): __snake_case : List[str] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(_lowerCAmelCase ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: __snake_case : Any = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(_lowerCAmelCase ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def snake_case__ ( self : int ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __snake_case : List[str] = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) __snake_case : Dict = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __snake_case : Union[str, Any] = tokenizer_r.encode_plus( _lowerCAmelCase , return_attention_mask=_lowerCAmelCase , return_token_type_ids=_lowerCAmelCase , return_offsets_mapping=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase , ) __snake_case : Optional[int] = tokenizer_r.do_lower_case if hasattr(_lowerCAmelCase , """do_lower_case""" ) else False __snake_case : List[Any] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def snake_case__ ( self : int ): __snake_case : Any = ["""的""", """人""", """有"""] __snake_case : Tuple = """""".join(_lowerCAmelCase ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __snake_case : List[Any] = True __snake_case : Optional[int] = self.tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) __snake_case : Dict = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) __snake_case : List[Any] = tokenizer_p.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) __snake_case : Optional[int] = tokenizer_r.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) __snake_case : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(_lowerCAmelCase ) __snake_case : Optional[int] = tokenizer_p.convert_ids_to_tokens(_lowerCAmelCase ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) __snake_case : Any = False __snake_case : List[str] = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) __snake_case : Union[str, Any] = self.tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) __snake_case : List[str] = tokenizer_r.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) __snake_case : Dict = tokenizer_p.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) __snake_case : Any = tokenizer_r.convert_ids_to_tokens(_lowerCAmelCase ) __snake_case : List[str] = tokenizer_p.convert_ids_to_tokens(_lowerCAmelCase ) # it is expected that only the first Chinese character is not preceded by "##". __snake_case : Tuple = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(_lowerCAmelCase ) ] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) @slow def snake_case__ ( self : Optional[int] ): __snake_case : List[str] = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __snake_case : Tuple = tokenizer.encode("""你好""" , add_special_tokens=_lowerCAmelCase ) __snake_case : Optional[int] = tokenizer.encode("""你是谁""" , add_special_tokens=_lowerCAmelCase ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase ) __snake_case : Dict = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def snake_case__ ( self : Dict ): __snake_case : Optional[int] = self.get_tokenizers(do_lower_case=_lowerCAmelCase ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __snake_case : List[Any] = """你好,你是谁""" __snake_case : List[str] = tokenizer.tokenize(_lowerCAmelCase ) __snake_case : List[Any] = tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) __snake_case : List[str] = tokenizer.convert_tokens_to_shape_ids(_lowerCAmelCase ) __snake_case : Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(_lowerCAmelCase ) __snake_case : Any = tokenizer.prepare_for_model( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) __snake_case : Any = tokenizer.encode_plus(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase )
359
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_blenderbot_small": [ "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotSmallConfig", "BlenderbotSmallOnnxConfig", ], "tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["BlenderbotSmallTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotSmallForCausalLM", "BlenderbotSmallForConditionalGeneration", "BlenderbotSmallModel", "BlenderbotSmallPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel", "TFBlenderbotSmallPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxBlenderbotSmallForConditionalGeneration", "FlaxBlenderbotSmallModel", "FlaxBlenderbotSmallPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
20
0
def lowercase_ ( _A : str ): """simple docstring""" return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
184
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class a__: def __init__( self : List[Any] , __snake_case : Union[str, Any] ): if isinstance(__snake_case , __snake_case ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden a : str = deepcopy(__snake_case ) elif os.path.exists(__snake_case ): with io.open(__snake_case , 'r' , encoding='utf-8' ) as f: a : Optional[Any] = json.load(__snake_case ) else: try: a : Any = baseaa.urlsafe_baadecode(__snake_case ).decode('utf-8' ) a : Union[str, Any] = json.loads(__snake_case ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) a : List[str] = config self.set_stage_and_offload() def lowercase_ ( self : List[str] ): # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. a : Dict = self.get_value('zero_optimization.stage' , -1 ) # offload a : str = False if self.is_zeroa() or self.is_zeroa(): a : Union[str, Any] = set(['cpu', 'nvme'] ) a : Optional[Any] = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: a : List[str] = True def lowercase_ ( self : Optional[Any] , __snake_case : Optional[Any] ): a : str = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) a : Dict = nodes.pop() for node in nodes: a : List[Any] = config.get(__snake_case ) if config is None: return None, ds_key return config, ds_key def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Any=None ): a , a : List[Any] = self.find_config_node(__snake_case ) if config is None: return default return config.get(__snake_case , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Any] , __snake_case : List[str]=False ): a : Optional[Any] = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) for node in nodes: a : str = config a : Dict = config.get(__snake_case ) if config is None: if must_exist: raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] ): a : Union[str, Any] = self.get_value(__snake_case ) return False if value is None else bool(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str ): a : Optional[Any] = self.get_value(__snake_case ) return False if value is None else not bool(__snake_case ) def lowercase_ ( self : Optional[Any] ): return self._stage == 2 def lowercase_ ( self : Union[str, Any] ): return self._stage == 3 def lowercase_ ( self : str ): return self._offload class a__: def __init__( self : Tuple , __snake_case : str ): a : Optional[Any] = engine def lowercase_ ( self : Union[str, Any] , __snake_case : str , **__snake_case : Tuple ): # runs backpropagation and handles mixed precision self.engine.backward(__snake_case , **__snake_case ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : List[str] ): super().__init__(__snake_case , device_placement=__snake_case , scaler=__snake_case ) a : Optional[Any] = hasattr(self.optimizer , 'overflow' ) def lowercase_ ( self : Dict , __snake_case : Dict=None ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def lowercase_ ( self : Optional[Any] ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def lowercase_ ( self : Tuple ): if self.__has_overflow__: return self.optimizer.overflow return False class a__( lowerCamelCase__ ): def __init__( self : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] ): super().__init__(__snake_case , __snake_case ) def lowercase_ ( self : Any ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class a__: def __init__( self : List[Any] , __snake_case : str , __snake_case : Dict=0.001 , __snake_case : Union[str, Any]=0 , **__snake_case : List[Any] ): a : Optional[Any] = params a : str = lr a : List[str] = weight_decay a : str = kwargs class a__: def __init__( self : str , __snake_case : Optional[Any] , __snake_case : List[str]=None , __snake_case : Tuple=0 , **__snake_case : Any ): a : Union[str, Any] = optimizer a : Any = total_num_steps a : List[str] = warmup_num_steps a : int = kwargs
297
0
'''simple docstring''' import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class __lowerCAmelCase ( __a ): snake_case : BigBirdConfig snake_case : jnp.dtype = jnp.floataa snake_case : bool = True def snake_case_ (self ): super().setup() _UpperCAmelCase : Tuple = nn.Dense(5 , dtype=self.dtype ) def __call__(self , *lowerCAmelCase__ , **lowerCAmelCase__ ): _UpperCAmelCase : int = super().__call__(*lowerCAmelCase__ , **lowerCAmelCase__ ) _UpperCAmelCase : List[Any] = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class __lowerCAmelCase ( __a ): snake_case : int = FlaxBigBirdForNaturalQuestionsModule def __A ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): def cross_entropy(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None ): _UpperCAmelCase : int = logits.shape[-1] _UpperCAmelCase : Optional[Any] = (labels[..., None] == jnp.arange(lowerCAmelCase_ )[None]).astype("""f4""" ) _UpperCAmelCase : List[Any] = jax.nn.log_softmax(lowerCAmelCase_ , axis=-1 ) _UpperCAmelCase : Optional[int] = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: _UpperCAmelCase : Optional[int] = reduction(lowerCAmelCase_ ) return loss _UpperCAmelCase : Any = partial(lowerCAmelCase_ , reduction=jnp.mean ) _UpperCAmelCase : Dict = cross_entropy(lowerCAmelCase_ , lowerCAmelCase_ ) _UpperCAmelCase : str = cross_entropy(lowerCAmelCase_ , lowerCAmelCase_ ) _UpperCAmelCase : Tuple = cross_entropy(lowerCAmelCase_ , lowerCAmelCase_ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class __lowerCAmelCase : snake_case : str = "google/bigbird-roberta-base" snake_case : int = 3_0_0_0 snake_case : int = 1_0_5_0_0 snake_case : int = 1_2_8 snake_case : int = 3 snake_case : int = 1 snake_case : int = 5 # tx_args snake_case : float = 3e-5 snake_case : float = 0.0 snake_case : int = 2_0_0_0_0 snake_case : float = 0.0_0_9_5 snake_case : str = "bigbird-roberta-natural-questions" snake_case : str = "training-expt" snake_case : str = "data/nq-training.jsonl" snake_case : str = "data/nq-validation.jsonl" def snake_case_ (self ): os.makedirs(self.base_dir , exist_ok=lowerCAmelCase__ ) _UpperCAmelCase : str = os.path.join(self.base_dir , self.save_dir ) _UpperCAmelCase : Tuple = self.batch_size_per_device * jax.device_count() @dataclass class __lowerCAmelCase : snake_case : int snake_case : int = 4_0_9_6 # no dynamic padding on TPUs def __call__(self , lowerCAmelCase__ ): _UpperCAmelCase : Optional[Any] = self.collate_fn(lowerCAmelCase__ ) _UpperCAmelCase : List[str] = jax.tree_util.tree_map(lowerCAmelCase__ , lowerCAmelCase__ ) return batch def snake_case_ (self , lowerCAmelCase__ ): _UpperCAmelCase : Optional[Any] = self.fetch_inputs(features["""input_ids"""] ) _UpperCAmelCase : Dict = { """input_ids""": jnp.array(lowerCAmelCase__ , dtype=jnp.intaa ), """attention_mask""": jnp.array(lowerCAmelCase__ , dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ), } return batch def snake_case_ (self , lowerCAmelCase__ ): _UpperCAmelCase : List[str] = [self._fetch_inputs(lowerCAmelCase__ ) for ids in input_ids] return zip(*lowerCAmelCase__ ) def snake_case_ (self , lowerCAmelCase__ ): _UpperCAmelCase : Optional[Any] = [1 for _ in range(len(lowerCAmelCase__ ) )] while len(lowerCAmelCase__ ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def __A ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None ): if seed is not None: _UpperCAmelCase : List[Any] = dataset.shuffle(seed=lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) // batch_size ): _UpperCAmelCase : List[str] = dataset[i * batch_size : (i + 1) * batch_size] yield dict(lowerCAmelCase_ ) @partial(jax.pmap , axis_name="""batch""" ) def __A ( lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ): def loss_fn(lowerCAmelCase_ ): _UpperCAmelCase : List[Any] = model_inputs.pop("""start_labels""" ) _UpperCAmelCase : Optional[Any] = model_inputs.pop("""end_labels""" ) _UpperCAmelCase : Any = model_inputs.pop("""pooled_labels""" ) _UpperCAmelCase : List[str] = state.apply_fn(**lowerCAmelCase_ , params=lowerCAmelCase_ , dropout_rng=lowerCAmelCase_ , train=lowerCAmelCase_ ) _UpperCAmelCase : Dict = outputs return state.loss_fn( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) _UpperCAmelCase : int = jax.random.split(lowerCAmelCase_ ) _UpperCAmelCase : int = jax.value_and_grad(lowerCAmelCase_ ) _UpperCAmelCase : Union[str, Any] = grad_fn(state.params ) _UpperCAmelCase : Any = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) _UpperCAmelCase : Tuple = jax.lax.pmean(lowerCAmelCase_ , """batch""" ) _UpperCAmelCase : Optional[int] = state.apply_gradients(grads=lowerCAmelCase_ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def __A ( lowerCAmelCase_ , **lowerCAmelCase_ ): _UpperCAmelCase : List[str] = model_inputs.pop("""start_labels""" ) _UpperCAmelCase : Optional[Any] = model_inputs.pop("""end_labels""" ) _UpperCAmelCase : List[str] = model_inputs.pop("""pooled_labels""" ) _UpperCAmelCase : Union[str, Any] = state.apply_fn(**lowerCAmelCase_ , params=state.params , train=lowerCAmelCase_ ) _UpperCAmelCase : List[str] = outputs _UpperCAmelCase : List[str] = state.loss_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _UpperCAmelCase : Tuple = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class __lowerCAmelCase ( train_state.TrainState ): snake_case : Callable = struct.field(pytree_node=__a ) @dataclass class __lowerCAmelCase : snake_case : Args snake_case : Callable snake_case : Callable snake_case : Callable snake_case : Callable snake_case : wandb snake_case : Callable = None def snake_case_ (self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None ): _UpperCAmelCase : Tuple = model.params _UpperCAmelCase : List[Any] = TrainState.create( apply_fn=model.__call__ , params=lowerCAmelCase__ , tx=lowerCAmelCase__ , loss_fn=lowerCAmelCase__ , ) if ckpt_dir is not None: _UpperCAmelCase : List[str] = restore_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCAmelCase : List[str] = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } _UpperCAmelCase : Union[str, Any] = build_tx(**lowerCAmelCase__ ) _UpperCAmelCase : List[Any] = train_state.TrainState( step=lowerCAmelCase__ , apply_fn=model.__call__ , params=lowerCAmelCase__ , tx=lowerCAmelCase__ , opt_state=lowerCAmelCase__ , ) _UpperCAmelCase : str = args _UpperCAmelCase : Optional[Any] = data_collator _UpperCAmelCase : List[Any] = lr _UpperCAmelCase : Optional[Any] = params _UpperCAmelCase : Tuple = jax_utils.replicate(lowerCAmelCase__ ) return state def snake_case_ (self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCAmelCase : int = self.args _UpperCAmelCase : Optional[int] = len(lowerCAmelCase__ ) // args.batch_size _UpperCAmelCase : Optional[Any] = jax.random.PRNGKey(0 ) _UpperCAmelCase : Optional[Any] = jax.random.split(lowerCAmelCase__ , jax.device_count() ) for epoch in range(args.max_epochs ): _UpperCAmelCase : int = jnp.array(0 , dtype=jnp.floataa ) _UpperCAmelCase : List[str] = get_batched_dataset(lowerCAmelCase__ , args.batch_size , seed=lowerCAmelCase__ ) _UpperCAmelCase : int = 0 for batch in tqdm(lowerCAmelCase__ , total=lowerCAmelCase__ , desc=F"Running EPOCH-{epoch}" ): _UpperCAmelCase : List[str] = self.data_collator(lowerCAmelCase__ ) _UpperCAmelCase : List[str] = self.train_step_fn(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: _UpperCAmelCase : str = jax_utils.unreplicate(state.step ) _UpperCAmelCase : Union[str, Any] = running_loss.item() / i _UpperCAmelCase : Optional[int] = self.scheduler_fn(state_step - 1 ) _UpperCAmelCase : Dict = self.evaluate(lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCAmelCase : str = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(lowerCAmelCase__ ) ) self.logger.log(lowerCAmelCase__ , commit=lowerCAmelCase__ ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"-e{epoch}-s{i}" , state=lowerCAmelCase__ ) def snake_case_ (self , lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCAmelCase : int = get_batched_dataset(lowerCAmelCase__ , self.args.batch_size ) _UpperCAmelCase : Any = len(lowerCAmelCase__ ) // self.args.batch_size _UpperCAmelCase : Dict = jnp.array(0 , dtype=jnp.floataa ) _UpperCAmelCase : Optional[Any] = 0 for batch in tqdm(lowerCAmelCase__ , total=lowerCAmelCase__ , desc="""Evaluating ... """ ): _UpperCAmelCase : Optional[Any] = self.data_collator(lowerCAmelCase__ ) _UpperCAmelCase : Optional[Any] = self.val_step_fn(lowerCAmelCase__ , **lowerCAmelCase__ ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def snake_case_ (self , lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCAmelCase : Any = jax_utils.unreplicate(lowerCAmelCase__ ) print(F"SAVING CHECKPOINT IN {save_dir}" , end=""" ... """ ) self.model_save_fn(lowerCAmelCase__ , params=state.params ) with open(os.path.join(lowerCAmelCase__ , """opt_state.msgpack""" ) , """wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(lowerCAmelCase__ , """args.joblib""" ) ) joblib.dump(self.data_collator , os.path.join(lowerCAmelCase__ , """data_collator.joblib""" ) ) with open(os.path.join(lowerCAmelCase__ , """training_state.json""" ) , """w""" ) as f: json.dump({"""step""": state.step.item()} , lowerCAmelCase__ ) print("""DONE""" ) def __A ( lowerCAmelCase_ , lowerCAmelCase_ ): print(f"RESTORING CHECKPOINT FROM {save_dir}" , end=""" ... """ ) with open(os.path.join(lowerCAmelCase_ , """flax_model.msgpack""" ) , """rb""" ) as f: _UpperCAmelCase : List[Any] = from_bytes(state.params , f.read() ) with open(os.path.join(lowerCAmelCase_ , """opt_state.msgpack""" ) , """rb""" ) as f: _UpperCAmelCase : Dict = from_bytes(state.opt_state , f.read() ) _UpperCAmelCase : Tuple = joblib.load(os.path.join(lowerCAmelCase_ , """args.joblib""" ) ) _UpperCAmelCase : int = joblib.load(os.path.join(lowerCAmelCase_ , """data_collator.joblib""" ) ) with open(os.path.join(lowerCAmelCase_ , """training_state.json""" ) , """r""" ) as f: _UpperCAmelCase : Tuple = json.load(lowerCAmelCase_ ) _UpperCAmelCase : int = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def __A ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : str = num_train_steps - warmup_steps _UpperCAmelCase : Any = optax.linear_schedule(init_value=lowerCAmelCase_ , end_value=lowerCAmelCase_ , transition_steps=lowerCAmelCase_ ) _UpperCAmelCase : Optional[int] = optax.linear_schedule(init_value=lowerCAmelCase_ , end_value=1e-7 , transition_steps=lowerCAmelCase_ ) _UpperCAmelCase : List[Any] = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def __A ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): def weight_decay_mask(lowerCAmelCase_ ): _UpperCAmelCase : Union[str, Any] = traverse_util.flatten_dict(lowerCAmelCase_ ) _UpperCAmelCase : List[Any] = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(lowerCAmelCase_ ) _UpperCAmelCase : Optional[int] = scheduler_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _UpperCAmelCase : Dict = optax.adamw(learning_rate=lowerCAmelCase_ , weight_decay=lowerCAmelCase_ , mask=lowerCAmelCase_ ) return tx, lr
354
'''simple docstring''' import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline lowerCAmelCase_ : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): snake_case : Optional[datasets.Features] = None snake_case : str = "utf-8" snake_case : Optional[str] = None snake_case : Optional[str] = None snake_case : bool = True # deprecated snake_case : Optional[int] = None # deprecated snake_case : int = 1_0 << 2_0 # 10MB snake_case : Optional[bool] = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): snake_case : Optional[int] = JsonConfig def snake_case_ (self ): if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) _UpperCAmelCase : List[Any] = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def snake_case_ (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 : Tuple = dl_manager.download_and_extract(self.config.data_files ) if isinstance(lowerCAmelCase__ , (str, list, tuple) ): _UpperCAmelCase : int = data_files if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCAmelCase : int = [files] _UpperCAmelCase : Any = [dl_manager.iter_files(lowerCAmelCase__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] _UpperCAmelCase : List[Any] = [] for split_name, files in data_files.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCAmelCase : Tuple = [files] _UpperCAmelCase : Union[str, Any] = [dl_manager.iter_files(lowerCAmelCase__ ) for file in files] splits.append(datasets.SplitGenerator(name=lowerCAmelCase__ , gen_kwargs={"""files""": files} ) ) return splits def snake_case_ (self , lowerCAmelCase__ ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): _UpperCAmelCase : Tuple = self.config.features.arrow_schema.field(lowerCAmelCase__ ).type _UpperCAmelCase : Any = pa_table.append_column(lowerCAmelCase__ , pa.array([None] * len(lowerCAmelCase__ ) , type=lowerCAmelCase__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example _UpperCAmelCase : Optional[int] = table_cast(lowerCAmelCase__ , self.config.features.arrow_schema ) return pa_table def snake_case_ (self , lowerCAmelCase__ ): for file_idx, file in enumerate(itertools.chain.from_iterable(lowerCAmelCase__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(lowerCAmelCase__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: _UpperCAmelCase : Optional[Any] = json.load(lowerCAmelCase__ ) # We keep only the field we are interested in _UpperCAmelCase : Tuple = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(lowerCAmelCase__ , (list, tuple) ): _UpperCAmelCase : Union[str, Any] = set().union(*[row.keys() for row in dataset] ) _UpperCAmelCase : Optional[int] = {col: [row.get(lowerCAmelCase__ ) for row in dataset] for col in keys} else: _UpperCAmelCase : Optional[int] = dataset _UpperCAmelCase : Any = pa.Table.from_pydict(lowerCAmelCase__ ) yield file_idx, self._cast_table(lowerCAmelCase__ ) # If the file has one json object per line else: with open(lowerCAmelCase__ , """rb""" ) as f: _UpperCAmelCase : Optional[int] = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small _UpperCAmelCase : List[Any] = max(self.config.chunksize // 3_2 , 1_6 << 1_0 ) _UpperCAmelCase : Union[str, Any] = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: _UpperCAmelCase : List[str] = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(lowerCAmelCase__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": _UpperCAmelCase : int = batch.decode(self.config.encoding , errors=lowerCAmelCase__ ).encode("""utf-8""" ) try: while True: try: _UpperCAmelCase : Tuple = paj.read_json( io.BytesIO(lowerCAmelCase__ ) , read_options=paj.ReadOptions(block_size=lowerCAmelCase__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(lowerCAmelCase__ , pa.ArrowInvalid ) and "straddling" not in str(lowerCAmelCase__ ) or block_size > len(lowerCAmelCase__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"Batch of {len(lowerCAmelCase__ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}." ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( lowerCAmelCase__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: _UpperCAmelCase : Optional[Any] = json.load(lowerCAmelCase__ ) except json.JSONDecodeError: logger.error(F"Failed to read file '{file}' with error {type(lowerCAmelCase__ )}: {e}" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): # list is the only sequence type supported in JSON try: _UpperCAmelCase : Tuple = set().union(*[row.keys() for row in dataset] ) _UpperCAmelCase : Dict = {col: [row.get(lowerCAmelCase__ ) for row in dataset] for col in keys} _UpperCAmelCase : int = pa.Table.from_pydict(lowerCAmelCase__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"Failed to read file '{file}' with error {type(lowerCAmelCase__ )}: {e}" ) raise ValueError(F"Not able to read records in the JSON file at {file}." ) from None yield file_idx, self._cast_table(lowerCAmelCase__ ) break else: logger.error(F"Failed to read file '{file}' with error {type(lowerCAmelCase__ )}: {e}" ) raise ValueError( F"Not able to read records in the JSON file at {file}. " F"You should probably indicate the field of the JSON file containing your records. " F"This JSON file contain the following fields: {str(list(dataset.keys() ) )}. " F"Select the correct one and provide it as `field='XXX'` to the dataset loading method. " ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(lowerCAmelCase__ ) batch_idx += 1
170
0
import logging import os import threading import time try: import warnings except ImportError: _snake_case : str = None try: import msvcrt except ImportError: _snake_case : List[Any] = None try: import fcntl except ImportError: _snake_case : Optional[Any] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: _snake_case : List[Any] = OSError # Data # ------------------------------------------------ _snake_case : Optional[Any] = [ "Timeout", "BaseFileLock", "WindowsFileLock", "UnixFileLock", "SoftFileLock", "FileLock", ] _snake_case : Optional[Any] = "3.0.12" _snake_case : str = None def lowerCAmelCase_ ( ): global _logger __snake_case : Optional[int] = _logger or logging.getLogger(__name__ ) return _logger class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Tuple ) -> List[str]: __snake_case : Optional[Any] = lock_file return None def __str__( self : str ) -> Union[str, Any]: __snake_case : List[str] = F'The file lock \'{self.lock_file}\' could not be acquired.' return temp class a : """simple docstring""" def __init__( self : int , lowerCamelCase : Optional[int] ) -> Any: __snake_case : Tuple = lock return None def __enter__( self : Union[str, Any] ) -> str: return self.lock def __exit__( self : str , lowerCamelCase : Tuple , lowerCamelCase : Union[str, Any] , lowerCamelCase : int ) -> Optional[int]: self.lock.release() return None class a : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase : str , lowerCamelCase : int=-1 , lowerCamelCase : Union[str, Any]=None ) -> Any: __snake_case : Optional[int] = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __snake_case : List[str] = self.hash_filename_if_too_long(lowerCamelCase , lowerCamelCase ) # The path to the lock file. __snake_case : str = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __snake_case : Any = None # The default timeout value. __snake_case : Dict = timeout # We use this lock primarily for the lock counter. __snake_case : Dict = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __snake_case : List[Any] = 0 return None @property def __snake_case ( self : List[str] ) -> Dict: return self._lock_file @property def __snake_case ( self : Optional[int] ) -> List[Any]: return self._timeout @timeout.setter def __snake_case ( self : int , lowerCamelCase : Tuple ) -> Union[str, Any]: __snake_case : List[str] = float(lowerCamelCase ) return None def __snake_case ( self : List[Any] ) -> Optional[int]: raise NotImplementedError() def __snake_case ( self : List[Any] ) -> str: raise NotImplementedError() @property def __snake_case ( self : List[Any] ) -> Tuple: return self._lock_file_fd is not None def __snake_case ( self : Union[str, Any] , lowerCamelCase : Any=None , lowerCamelCase : Any=0.05 ) -> str: # Use the default timeout, if no timeout is provided. if timeout is None: __snake_case : Tuple = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __snake_case : Dict = id(self ) __snake_case : Tuple = self._lock_file __snake_case : Any = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(F'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(F'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(F'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( F'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(lowerCamelCase ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __snake_case : List[str] = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def __snake_case ( self : Tuple , lowerCamelCase : Dict=False ) -> str: with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __snake_case : Optional[Any] = id(self ) __snake_case : List[str] = self._lock_file logger().debug(F'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __snake_case : Any = 0 logger().debug(F'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Any ) -> Tuple: self.acquire() return self def __exit__( self : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] , lowerCamelCase : Any ) -> Optional[Any]: self.release() return None def __del__( self : Optional[int] ) -> List[str]: self.release(force=lowerCamelCase ) return None def __snake_case ( self : Optional[Any] , lowerCamelCase : str , lowerCamelCase : int ) -> str: __snake_case : List[Any] = os.path.basename(lowerCamelCase ) if len(lowerCamelCase ) > max_length and max_length > 0: __snake_case : Tuple = os.path.dirname(lowerCamelCase ) __snake_case : Tuple = str(hash(lowerCamelCase ) ) __snake_case : Any = filename[: max_length - len(lowerCamelCase ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(lowerCamelCase , lowerCamelCase ) else: return path class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[Any] , lowerCamelCase : Any , lowerCamelCase : Optional[int]=-1 , lowerCamelCase : List[Any]=None ) -> int: from .file_utils import relative_to_absolute_path super().__init__(lowerCamelCase , timeout=lowerCamelCase , max_filename_length=lowerCamelCase ) __snake_case : Tuple = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def __snake_case ( self : int ) -> List[Any]: __snake_case : Any = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __snake_case : Optional[int] = os.open(self._lock_file , lowerCamelCase ) except OSError: pass else: try: msvcrt.locking(lowerCamelCase , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(lowerCamelCase ) else: __snake_case : Union[str, Any] = fd return None def __snake_case ( self : List[Any] ) -> Tuple: __snake_case : Dict = self._lock_file_fd __snake_case : int = None msvcrt.locking(lowerCamelCase , msvcrt.LK_UNLCK , 1 ) os.close(lowerCamelCase ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Tuple , lowerCamelCase : List[Any]=-1 , lowerCamelCase : Tuple=None ) -> str: __snake_case : List[str] = os.statvfs(os.path.dirname(lowerCamelCase ) ).f_namemax super().__init__(lowerCamelCase , timeout=lowerCamelCase , max_filename_length=lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> List[str]: __snake_case : int = os.O_RDWR | os.O_CREAT | os.O_TRUNC __snake_case : Optional[int] = os.open(self._lock_file , lowerCamelCase ) try: fcntl.flock(lowerCamelCase , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(lowerCamelCase ) else: __snake_case : int = fd return None def __snake_case ( self : Optional[int] ) -> Any: # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition __snake_case : List[Any] = self._lock_file_fd __snake_case : List[Any] = None fcntl.flock(lowerCamelCase , fcntl.LOCK_UN ) os.close(lowerCamelCase ) return None class a (_lowerCAmelCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> Union[str, Any]: __snake_case : Optional[Any] = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __snake_case : Dict = os.open(self._lock_file , lowerCamelCase ) except OSError: pass else: __snake_case : Tuple = fd return None def __snake_case ( self : str ) -> Any: os.close(self._lock_file_fd ) __snake_case : Tuple = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None _snake_case : Optional[Any] = None if msvcrt: _snake_case : int = WindowsFileLock elif fcntl: _snake_case : Optional[Any] = UnixFileLock else: _snake_case : Any = SoftFileLock if warnings is not None: warnings.warn("only soft file lock is available")
123
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 _snake_case : Tuple = logging.get_logger(__name__) _snake_case : Optional[Any] = { "facebook/data2vec-vision-base-ft": ( "https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json" ), } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Any = "data2vec-vision" def __init__( self : Optional[int] , lowerCamelCase : int=768 , lowerCamelCase : Optional[Any]=12 , lowerCamelCase : Optional[int]=12 , lowerCamelCase : Union[str, Any]=3072 , lowerCamelCase : Tuple="gelu" , lowerCamelCase : List[Any]=0.0 , lowerCamelCase : Tuple=0.0 , lowerCamelCase : List[Any]=0.02 , lowerCamelCase : int=1E-12 , lowerCamelCase : Optional[int]=224 , lowerCamelCase : List[str]=16 , lowerCamelCase : str=3 , lowerCamelCase : Any=False , lowerCamelCase : Tuple=False , lowerCamelCase : List[str]=False , lowerCamelCase : Optional[int]=False , lowerCamelCase : List[Any]=0.1 , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Dict=True , lowerCamelCase : Tuple=[3, 5, 7, 11] , lowerCamelCase : Union[str, Any]=[1, 2, 3, 6] , lowerCamelCase : List[str]=True , lowerCamelCase : int=0.4 , lowerCamelCase : Optional[int]=256 , lowerCamelCase : Tuple=1 , lowerCamelCase : Tuple=False , lowerCamelCase : Any=255 , **lowerCamelCase : str , ) -> Optional[int]: super().__init__(**lowerCamelCase ) __snake_case : Dict = hidden_size __snake_case : str = num_hidden_layers __snake_case : str = num_attention_heads __snake_case : Tuple = intermediate_size __snake_case : int = hidden_act __snake_case : Optional[int] = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Union[str, Any] = initializer_range __snake_case : Optional[Any] = layer_norm_eps __snake_case : Tuple = image_size __snake_case : Tuple = patch_size __snake_case : Optional[Any] = num_channels __snake_case : Optional[Any] = use_mask_token __snake_case : Dict = use_absolute_position_embeddings __snake_case : Optional[Any] = use_relative_position_bias __snake_case : Any = use_shared_relative_position_bias __snake_case : Union[str, Any] = layer_scale_init_value __snake_case : List[Any] = drop_path_rate __snake_case : Any = use_mean_pooling # decode head attributes (semantic segmentation) __snake_case : Optional[int] = out_indices __snake_case : List[str] = pool_scales # auxiliary head attributes (semantic segmentation) __snake_case : int = use_auxiliary_head __snake_case : Optional[Any] = auxiliary_loss_weight __snake_case : Optional[int] = auxiliary_channels __snake_case : str = auxiliary_num_convs __snake_case : Any = auxiliary_concat_input __snake_case : Optional[Any] = semantic_loss_ignore_index class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = version.parse("1.11" ) @property def __snake_case ( self : int ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __snake_case ( self : List[Any] ) -> float: return 1E-4
123
1
def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> float: a = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("""All input parameters must be positive""" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("""Relative densities cannot be greater than one""" ) else: a = 1 - (matter_density + radiation_density + dark_energy) a = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) a = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation __UpperCamelCase : Union[str, Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
361
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = CanineTokenizer UpperCamelCase__ = False def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' super().setUp() a = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCamelCase__ ( self :Dict ): '''simple docstring''' return CanineTokenizer.from_pretrained("""google/canine-s""" ) def lowerCamelCase__ ( self :Tuple , **__magic_name__ :Dict ): '''simple docstring''' a = self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) a = 1024 return tokenizer @require_torch def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.canine_tokenizer a = ["""Life is like a box of chocolates.""", """You never know what you're gonna get."""] # fmt: off a = [5_7344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 5_7345, 0, 0, 0, 0] # fmt: on a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) self.assertIsInstance(__magic_name__ , __magic_name__ ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = ["""Once there was a man.""", """He wrote a test in HuggingFace Tranformers."""] a = tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors="""pt""" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("""input_ids""" , __magic_name__ ) self.assertIn("""attention_mask""" , __magic_name__ ) self.assertIn("""token_type_ids""" , __magic_name__ ) @require_torch def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = self.canine_tokenizer a = [ """What's the weater?""", """It's about 25 degrees.""", ] a = tokenizer( text_target=__magic_name__ , max_length=32 , padding="""max_length""" , truncation=__magic_name__ , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) shutil.rmtree(__magic_name__ ) a = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc a = tempfile.mkdtemp() a = """ He is very happy, UNwant\u00E9d,running""" a = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: a = chr(0Xe_0_0_7 ) additional_special_tokens.append(__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) a = tokenizer.__class__.from_pretrained(__magic_name__ ) a = after_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertIn(__magic_name__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) a = tokenizer.__class__.from_pretrained(__magic_name__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a , a = self.get_clean_sequence(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_5 a = chr(__magic_name__ ) tokenizer.add_special_tokens({"""cls_token""": special_token} ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) a = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , input_encoded + special_token_id ) a = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertTrue(special_token not in decoded ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = chr(0Xe_0_0_5 ) a = chr(0Xe_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=__magic_name__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"""additional_special_tokens""": [SPECIAL_TOKEN_2]} ) a = tokenizer.tokenize(__magic_name__ ) a = tokenizer.tokenize(__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(token_a[0] , __magic_name__ ) self.assertEqual(token_a[0] , __magic_name__ ) @require_tokenizers def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(__magic_name__ ) tokenizer.from_pretrained(__magic_name__ ) def lowerCamelCase__ ( self :int ): '''simple docstring''' a = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__magic_name__ ) with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: a = json.load(__magic_name__ ) # a special token for Canine can be defined as follows: a = 0Xe_0_0_6 a = chr(__magic_name__ ) a = [new_token_a] a = [new_token_a] with open(os.path.join(__magic_name__ , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__magic_name__ , __magic_name__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files a = tokenizer_class.from_pretrained(__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) a = 0Xe_0_0_7 a = chr(__magic_name__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained a = [AddedToken(__magic_name__ , lstrip=__magic_name__ )] a = tokenizer_class.from_pretrained( __magic_name__ , additional_special_tokens=__magic_name__ , extra_ids=0 ) self.assertIn(__magic_name__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = """hello world""" if self.space_between_special_tokens: a = """[CLS] hello world [SEP]""" else: a = input a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) a = tokenizer.decode(__magic_name__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(__magic_name__ , [output, output.lower()] ) def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): a = [ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] a = """a""" a = ord(__magic_name__ ) for attr in attributes_list: setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , attr + """_id""" , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , __magic_name__ ) , __magic_name__ ) self.assertEqual(getattr(__magic_name__ , attr + """_id""" ) , __magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [] ) a = 0Xe_0_0_6 a = chr(__magic_name__ ) setattr(__magic_name__ , """additional_special_tokens_ids""" , [additional_special_token_id] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens""" ) , [additional_special_token] ) self.assertListEqual(getattr(__magic_name__ , """additional_special_tokens_ids""" ) , [additional_special_token_id] ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :str ): '''simple docstring''' pass def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass def lowerCamelCase__ ( self :Any ): '''simple docstring''' pass def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' pass
347
0
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _UpperCamelCase = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) def _lowercase ( lowercase__ ): __lowerCAmelCase : Any = test_results.split(''' ''' ) __lowerCAmelCase : List[Any] = 0 __lowerCAmelCase : int = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. __lowerCAmelCase : List[Any] = expressions[-2] if '''=''' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase__ ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _lowercase ( lowercase__ ): __lowerCAmelCase : str = {} __lowerCAmelCase : Dict = None __lowerCAmelCase : Any = False for line in failures_short_lines.split('''\n''' ): if re.search(r'''_ \[doctest\]''' , lowercase__ ): __lowerCAmelCase : int = True __lowerCAmelCase : Optional[Any] = line.split(''' ''' )[2] elif in_error and not line.split(''' ''' )[0].isdigit(): __lowerCAmelCase : Tuple = line __lowerCAmelCase : Optional[Any] = False return failures class __lowercase : def __init__( self , A_ , A_ ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : List[Any] = title __lowerCAmelCase : Optional[int] = doc_test_results['''time_spent'''].split(''',''' )[0] __lowerCAmelCase : Any = doc_test_results['''success'''] __lowerCAmelCase : Optional[int] = doc_test_results['''failures'''] __lowerCAmelCase : Union[str, Any] = self.n_success + self.n_failures # Failures and success of the modeling tests __lowerCAmelCase : Tuple = doc_test_results @property def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Optional[int] = [self._time_spent] __lowerCAmelCase : Optional[Any] = 0 for time in time_spent: __lowerCAmelCase : int = time.split(''':''' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(A_ ) == 1: __lowerCAmelCase : List[Any] = [0, 0, time_parts[0]] __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Union[str, Any] = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 3600 + minutes * 60 + seconds __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Union[str, Any] = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return f"""{int(A_ )}h{int(A_ )}m{int(A_ )}s""" @property def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' return { "type": "section", "text": { "type": "plain_text", "text": f"""🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.""", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f"""https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}""", }, } @property def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' return { "type": "section", "text": { "type": "plain_text", "text": ( f"""There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in""" f""" {self.time}.""" ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f"""https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}""", }, } @property def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : int = 40 __lowerCAmelCase : Optional[Any] = {k: v['''failed'''] for k, v in doc_test_results.items() if isinstance(A_ , A_ )} __lowerCAmelCase : Dict = '''''' for category, failures in category_failures.items(): if len(A_ ) == 0: continue if report != "": report += "\n\n" report += f"""*{category} failures*:""".ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(A_ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f"""The following examples had failures:\n\n\n{report}\n""", }, } @property def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(A_ ) @staticmethod def UpperCamelCase__ ( ) ->Any: '''simple docstring''' __lowerCAmelCase : Optional[Any] = [ { '''type''': '''section''', '''text''': { '''type''': '''plain_text''', '''text''': '''There was an issue running the tests.''', }, '''accessory''': { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''Check Action results''', '''emoji''': True}, '''url''': f"""https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}""", }, } ] print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(A_ )} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text='''There was an issue running the tests.''' , blocks=A_ , ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(self.payload )} ) ) __lowerCAmelCase : List[Any] = f"""{self.n_failures} failures out of {self.n_tests} tests,""" if self.n_failures else '''All tests passed.''' __lowerCAmelCase : Optional[Any] = client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , blocks=self.payload , text=A_ , ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ ) ->str: '''simple docstring''' __lowerCAmelCase : Optional[int] = '''''' for key, value in failures.items(): __lowerCAmelCase : Tuple = value[:200] + ''' [Truncated]''' if len(A_ ) > 250 else value failures_text += f"""*{key}*\n_{value}_\n\n""" __lowerCAmelCase : Union[str, Any] = job_name __lowerCAmelCase : Dict = {'''type''': '''section''', '''text''': {'''type''': '''mrkdwn''', '''text''': text}} if job_link is not None: __lowerCAmelCase : List[Any] = { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''GitHub Action job''', '''emoji''': True}, '''url''': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def UpperCamelCase__ ( self ) ->int: '''simple docstring''' if self.thread_ts is None: raise ValueError('''Can only post reply if a post has been made.''' ) __lowerCAmelCase : Optional[Any] = self.doc_test_results.pop('''job_link''' ) self.doc_test_results.pop('''failures''' ) self.doc_test_results.pop('''success''' ) self.doc_test_results.pop('''time_spent''' ) __lowerCAmelCase : List[str] = sorted(self.doc_test_results.items() , key=lambda A_ : t[0] ) for job, job_result in sorted_dict: if len(job_result['''failures'''] ): __lowerCAmelCase : List[Any] = f"""*Num failures* :{len(job_result["failed"] )} \n""" __lowerCAmelCase : List[str] = job_result['''failures'''] __lowerCAmelCase : Any = self.get_reply_blocks(A_ , A_ , A_ , text=A_ ) print('''Sending the following reply''' ) print(json.dumps({'''blocks''': blocks} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text=f"""Results for {job}""" , blocks=A_ , thread_ts=self.thread_ts['''ts'''] , ) time.sleep(1 ) def _lowercase ( ): __lowerCAmelCase : Dict = os.environ['''GITHUB_RUN_ID'''] __lowerCAmelCase : Optional[int] = f"""https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100""" __lowerCAmelCase : Tuple = requests.get(lowercase__ ).json() __lowerCAmelCase : List[Any] = {} try: jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) __lowerCAmelCase : List[str] = math.ceil((result['''total_count'''] - 1_0_0) / 1_0_0 ) for i in range(lowercase__ ): __lowerCAmelCase : Optional[int] = requests.get(url + f"""&page={i + 2}""" ).json() jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) return jobs except Exception as e: print('''Unknown error, could not fetch links.''' , lowercase__ ) return {} def _lowercase ( lowercase__ ): __lowerCAmelCase : Dict = {} if os.path.exists(lowercase__ ): __lowerCAmelCase : Optional[int] = os.listdir(lowercase__ ) for file in files: try: with open(os.path.join(lowercase__ , lowercase__ ) , encoding='''utf-8''' ) as f: __lowerCAmelCase : Optional[int] = f.read() except UnicodeDecodeError as e: raise ValueError(f"""Could not open {os.path.join(lowercase__ , lowercase__ )}.""" ) from e return _artifact def _lowercase ( ): class __lowercase : def __init__( self , A_ ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : Optional[int] = name __lowerCAmelCase : Any = [] def __str__( self ) ->Optional[int]: '''simple docstring''' return self.name def UpperCamelCase__ ( self , A_ ) ->Any: '''simple docstring''' self.paths.append({'''name''': self.name, '''path''': path} ) __lowerCAmelCase : Dict[str, Artifact] = {} __lowerCAmelCase : Union[str, Any] = filter(os.path.isdir , os.listdir() ) for directory in directories: __lowerCAmelCase : List[Any] = directory if artifact_name not in _available_artifacts: __lowerCAmelCase : Optional[int] = Artifact(lowercase__ ) _available_artifacts[artifact_name].add_path(lowercase__ ) return _available_artifacts if __name__ == "__main__": _UpperCamelCase = get_job_links() _UpperCamelCase = retrieve_available_artifacts() _UpperCamelCase = collections.OrderedDict( [ ("*.py", "API Examples"), ("*.md", "MD Examples"), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _UpperCamelCase = { v: { "failed": [], "failures": {}, } for v in docs.values() } # Link to the GitHub Action job _UpperCamelCase = github_actions_job_links.get("run_doctests") _UpperCamelCase = available_artifacts["doc_tests_gpu_test_reports"].paths[0] _UpperCamelCase = retrieve_artifact(artifact_path["name"]) if "stats" in artifact: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = handle_test_results(artifact["stats"]) _UpperCamelCase = failed _UpperCamelCase = success _UpperCamelCase = time_spent[1:-1] + ", " _UpperCamelCase = extract_first_line_failure(artifact["failures_short"]) for line in artifact["summary_short"].split("\n"): if re.search("FAILED", line): _UpperCamelCase = line.replace("FAILED ", "") _UpperCamelCase = line.split()[0].replace("\n", "") if "::" in line: _UpperCamelCase , _UpperCamelCase = line.split("::") else: _UpperCamelCase , _UpperCamelCase = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _UpperCamelCase = docs[file_regex] doc_test_results[category]["failed"].append(test) _UpperCamelCase = all_failures[test] if test in all_failures else "N/A" _UpperCamelCase = failure break _UpperCamelCase = Message("🤗 Results of the doc tests.", doc_test_results) message.post() message.post_reply()
275
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "adapter_layer": "encoder.layers.*.adapter_layer", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", "pooling_layer.linear": "projector", "pooling_layer.projection": "classifier", } _UpperCamelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "projector", "classifier", ] def _lowercase ( lowercase__ ): __lowerCAmelCase : List[str] = {} with open(lowercase__ , '''r''' ) as file: for line_number, line in enumerate(lowercase__ ): __lowerCAmelCase : Any = line.strip() if line: __lowerCAmelCase : Dict = line.split() __lowerCAmelCase : str = line_number __lowerCAmelCase : List[str] = words[0] __lowerCAmelCase : Any = value return result def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): for attribute in key.split('''.''' ): __lowerCAmelCase : List[Any] = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : Any = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowercase__ ): __lowerCAmelCase : Tuple = PARAM_MAPPING[full_name.split('''.''' )[-1]] __lowerCAmelCase : List[Any] = '''param''' if weight_type is not None and weight_type != "param": __lowerCAmelCase : str = getattr(lowercase__ , lowercase__ ).shape elif weight_type is not None and weight_type == "param": __lowerCAmelCase : Dict = hf_pointer for attribute in hf_param_name.split('''.''' ): __lowerCAmelCase : Dict = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : str = shape_pointer.shape # let's reduce dimension __lowerCAmelCase : Any = value[0] else: __lowerCAmelCase : str = 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": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[str] = value elif weight_type == "weight_v": __lowerCAmelCase : int = value elif weight_type == "bias": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('''.''' ): __lowerCAmelCase : Dict = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : Tuple = value else: __lowerCAmelCase : Any = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : Any = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowercase__ ): __lowerCAmelCase : str = PARAM_MAPPING[full_name.split('''.''' )[-1]] __lowerCAmelCase : int = '''param''' if weight_type is not None and weight_type != "param": __lowerCAmelCase : Tuple = '''.'''.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __lowerCAmelCase : List[str] = '''.'''.join([key, hf_param_name] ) else: __lowerCAmelCase : Optional[int] = key __lowerCAmelCase : Union[str, Any] = value if '''lm_head''' in full_key else value[0] _UpperCamelCase = { "W_a": "linear_1.weight", "W_b": "linear_2.weight", "b_a": "linear_1.bias", "b_b": "linear_2.bias", "ln_W": "norm.weight", "ln_b": "norm.bias", } def _lowercase ( lowercase__ , lowercase__ , lowercase__=None , lowercase__=None ): __lowerCAmelCase : Any = False for key, mapped_key in MAPPING.items(): __lowerCAmelCase : Tuple = '''wav2vec2.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __lowerCAmelCase : Optional[Any] = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(lowercase__ )[0].split('''.''' )[-2] __lowerCAmelCase : Dict = mapped_key.replace('''*''' , lowercase__ ) if "weight_g" in name: __lowerCAmelCase : List[Any] = '''weight_g''' elif "weight_v" in name: __lowerCAmelCase : List[Any] = '''weight_v''' elif "bias" in name: __lowerCAmelCase : Any = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : int = '''weight''' else: __lowerCAmelCase : Any = None if hf_dict is not None: rename_dict(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) else: set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return is_used return is_used def _lowercase ( lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : List[str] = [] __lowerCAmelCase : Optional[Any] = fairseq_model.state_dict() __lowerCAmelCase : Tuple = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Any = False if "conv_layers" in name: load_conv_layer( lowercase__ , lowercase__ , lowercase__ , lowercase__ , hf_model.config.feat_extract_norm == '''group''' , ) __lowerCAmelCase : int = True else: __lowerCAmelCase : Dict = load_wavaveca_layer(lowercase__ , lowercase__ , lowercase__ ) if not is_used: unused_weights.append(lowercase__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : Any = full_name.split('''conv_layers.''' )[-1] __lowerCAmelCase : List[str] = name.split('''.''' ) __lowerCAmelCase : Any = int(items[0] ) __lowerCAmelCase : str = 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.""" ) __lowerCAmelCase : List[str] = 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.""" ) __lowerCAmelCase : List[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.""" ) __lowerCAmelCase : 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.""" ) __lowerCAmelCase : Optional[int] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(lowercase__ ) @torch.no_grad() def _lowercase ( lowercase__ , lowercase__ , lowercase__=None , lowercase__=None , lowercase__=True , lowercase__=False ): if config_path is not None: __lowerCAmelCase : Union[str, Any] = WavaVecaConfig.from_pretrained(lowercase__ ) else: __lowerCAmelCase : Optional[int] = WavaVecaConfig() if is_seq_class: __lowerCAmelCase : Optional[Any] = read_txt_into_dict(lowercase__ ) __lowerCAmelCase : int = idalabel __lowerCAmelCase : Optional[int] = WavaVecaForSequenceClassification(lowercase__ ) __lowerCAmelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowercase__ , return_attention_mask=lowercase__ , ) feature_extractor.save_pretrained(lowercase__ ) elif is_finetuned: if dict_path: __lowerCAmelCase : List[str] = Dictionary.load(lowercase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowerCAmelCase : List[Any] = target_dict.pad_index __lowerCAmelCase : List[Any] = target_dict.bos_index __lowerCAmelCase : Optional[int] = target_dict.eos_index __lowerCAmelCase : Any = len(target_dict.symbols ) __lowerCAmelCase : Union[str, Any] = os.path.join(lowercase__ , '''vocab.json''' ) if not os.path.isdir(lowercase__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowercase__ ) ) return os.makedirs(lowercase__ , exist_ok=lowercase__ ) __lowerCAmelCase : Optional[int] = target_dict.indices # fairseq has the <pad> and <s> switched __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : int = 1 with open(lowercase__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(lowercase__ , lowercase__ ) __lowerCAmelCase : Dict = WavaVecaCTCTokenizer( lowercase__ , 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=lowercase__ , ) __lowerCAmelCase : List[str] = True if config.feat_extract_norm == '''layer''' else False __lowerCAmelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowercase__ , return_attention_mask=lowercase__ , ) __lowerCAmelCase : List[Any] = WavaVecaProcessor(feature_extractor=lowercase__ , tokenizer=lowercase__ ) processor.save_pretrained(lowercase__ ) __lowerCAmelCase : str = WavaVecaForCTC(lowercase__ ) else: __lowerCAmelCase : Any = WavaVecaForPreTraining(lowercase__ ) if is_finetuned or is_seq_class: __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __lowerCAmelCase : Union[str, Any] = argparse.Namespace(task='''audio_pretraining''' ) __lowerCAmelCase : str = fairseq.tasks.setup_task(lowercase__ ) __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowercase__ ) __lowerCAmelCase : int = model[0].eval() recursively_load_weights(lowercase__ , lowercase__ , not is_finetuned ) hf_wavavec.save_pretrained(lowercase__ ) 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" ) parser.add_argument( "--is_seq_class", action="store_true", help="Whether the model to convert is a fine-tuned sequence classification model or not", ) _UpperCamelCase = parser.parse_args() _UpperCamelCase = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
275
1
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class snake_case_ : def __init__( self : Union[str, Any] , _snake_case : Collection[float] | None = None )->None: '''simple docstring''' if components is None: __lowerCAmelCase : str = [] __lowerCAmelCase : List[str] = list(_snake_case ) def __len__( self : Any )->int: '''simple docstring''' return len(self.__components ) def __str__( self : Optional[Any] )->str: '''simple docstring''' return "(" + ",".join(map(_snake_case , self.__components ) ) + ")" def __add__( self : Union[str, Any] , _snake_case : Vector )->Vector: '''simple docstring''' __lowerCAmelCase : List[Any] = len(self ) if size == len(_snake_case ): __lowerCAmelCase : Union[str, Any] = [self.__components[i] + other.component(_snake_case ) for i in range(_snake_case )] return Vector(_snake_case ) else: raise Exception("""must have the same size""" ) def __sub__( self : Optional[Any] , _snake_case : Vector )->Vector: '''simple docstring''' __lowerCAmelCase : List[Any] = len(self ) if size == len(_snake_case ): __lowerCAmelCase : Dict = [self.__components[i] - other.component(_snake_case ) for i in range(_snake_case )] return Vector(_snake_case ) else: # error case raise Exception("""must have the same size""" ) @overload def __mul__( self : Optional[int] , _snake_case : float )->Vector: '''simple docstring''' ... @overload def __mul__( self : Union[str, Any] , _snake_case : Vector )->float: '''simple docstring''' ... def __mul__( self : Optional[int] , _snake_case : float | Vector )->float | Vector: '''simple docstring''' if isinstance(_snake_case , (float, int) ): __lowerCAmelCase : Optional[int] = [c * other for c in self.__components] return Vector(_snake_case ) elif isinstance(_snake_case , _snake_case ) and len(self ) == len(_snake_case ): __lowerCAmelCase : Any = len(self ) __lowerCAmelCase : int = [self.__components[i] * other.component(_snake_case ) for i in range(_snake_case )] return sum(_snake_case ) else: # error case raise Exception("""invalid operand!""" ) def UpperCAmelCase__ ( self : int )->Vector: '''simple docstring''' return Vector(self.__components ) def UpperCAmelCase__ ( self : Optional[Any] , _snake_case : int )->float: '''simple docstring''' if isinstance(_snake_case , _snake_case ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("""index out of range""" ) def UpperCAmelCase__ ( self : Union[str, Any] , _snake_case : int , _snake_case : float )->None: '''simple docstring''' assert -len(self.__components ) <= pos < len(self.__components ) __lowerCAmelCase : Union[str, Any] = value def UpperCAmelCase__ ( self : Optional[int] )->float: '''simple docstring''' if len(self.__components ) == 0: raise Exception("""Vector is empty""" ) __lowerCAmelCase : int = [c**2 for c in self.__components] return math.sqrt(sum(_snake_case ) ) def UpperCAmelCase__ ( self : List[Any] , _snake_case : Vector , _snake_case : bool = False )->float: '''simple docstring''' __lowerCAmelCase : Optional[Any] = self * other __lowerCAmelCase : Optional[int] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int ) -> Vector: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int ) -> Vector: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and (isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )) __lowerCAmelCase : List[str] = [0] * dimension __lowerCAmelCase : Optional[int] = 1 return Vector(SCREAMING_SNAKE_CASE ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :float , SCREAMING_SNAKE_CASE :Vector , SCREAMING_SNAKE_CASE :Vector ) -> Vector: assert ( isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and (isinstance(SCREAMING_SNAKE_CASE , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int ) -> Vector: random.seed(SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [random.randint(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for _ in range(SCREAMING_SNAKE_CASE )] return Vector(SCREAMING_SNAKE_CASE ) class snake_case_ : def __init__( self : List[str] , _snake_case : list[list[float]] , _snake_case : int , _snake_case : int )->None: '''simple docstring''' __lowerCAmelCase : Any = matrix __lowerCAmelCase : List[Any] = w __lowerCAmelCase : Any = h def __str__( self : Dict )->str: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = """""" for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : Optional[Any] , _snake_case : Matrix )->Matrix: '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): __lowerCAmelCase : Union[str, Any] = [] for i in range(self.__height ): __lowerCAmelCase : int = [ self.__matrix[i][j] + other.component(_snake_case , _snake_case ) for j in range(self.__width ) ] matrix.append(_snake_case ) return Matrix(_snake_case , self.__width , self.__height ) else: raise Exception("""matrix must have the same dimension!""" ) def __sub__( self : int , _snake_case : Matrix )->Matrix: '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): __lowerCAmelCase : int = [] for i in range(self.__height ): __lowerCAmelCase : Optional[Any] = [ self.__matrix[i][j] - other.component(_snake_case , _snake_case ) for j in range(self.__width ) ] matrix.append(_snake_case ) return Matrix(_snake_case , self.__width , self.__height ) else: raise Exception("""matrices must have the same dimension!""" ) @overload def __mul__( self : Optional[Any] , _snake_case : float )->Matrix: '''simple docstring''' ... @overload def __mul__( self : str , _snake_case : Vector )->Vector: '''simple docstring''' ... def __mul__( self : Dict , _snake_case : float | Vector )->Vector | Matrix: '''simple docstring''' if isinstance(_snake_case , _snake_case ): # matrix-vector if len(_snake_case ) == self.__width: __lowerCAmelCase : Optional[int] = zero_vector(self.__height ) for i in range(self.__height ): __lowerCAmelCase : Optional[int] = [ self.__matrix[i][j] * other.component(_snake_case ) for j in range(self.__width ) ] ans.change_component(_snake_case , sum(_snake_case ) ) return ans else: raise Exception( """vector must have the same size as the """ """number of columns of the matrix!""" ) elif isinstance(_snake_case , (int, float) ): # matrix-scalar __lowerCAmelCase : Tuple = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_snake_case , self.__width , self.__height ) return None def UpperCAmelCase__ ( self : Optional[Any] )->int: '''simple docstring''' return self.__height def UpperCAmelCase__ ( self : List[str] )->int: '''simple docstring''' return self.__width def UpperCAmelCase__ ( self : Any , _snake_case : int , _snake_case : int )->float: '''simple docstring''' if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("""change_component: indices out of bounds""" ) def UpperCAmelCase__ ( self : int , _snake_case : int , _snake_case : int , _snake_case : float )->None: '''simple docstring''' if 0 <= x < self.__height and 0 <= y < self.__width: __lowerCAmelCase : str = value else: raise Exception("""change_component: indices out of bounds""" ) def UpperCAmelCase__ ( self : List[Any] , _snake_case : int , _snake_case : int )->float: '''simple docstring''' if self.__height != self.__width: raise Exception("""Matrix is not square""" ) __lowerCAmelCase : str = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_snake_case ) ): __lowerCAmelCase : Any = minor[i][:y] + minor[i][y + 1 :] return Matrix(_snake_case , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase__ ( self : List[str] , _snake_case : int , _snake_case : int )->float: '''simple docstring''' if self.__height != self.__width: raise Exception("""Matrix is not square""" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_snake_case , _snake_case ) else: raise Exception("""Indices out of bounds""" ) def UpperCAmelCase__ ( self : Dict )->float: '''simple docstring''' if self.__height != self.__width: raise Exception("""Matrix is not square""" ) if self.__height < 1: raise Exception("""Matrix has no element""" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __lowerCAmelCase : int = [ self.__matrix[0][y] * self.cofactor(0 , _snake_case ) for y in range(self.__width ) ] return sum(_snake_case ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int ) -> Matrix: __lowerCAmelCase : list[list[float]] = [[0] * n for _ in range(SCREAMING_SNAKE_CASE )] return Matrix(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int ) -> Matrix: random.seed(SCREAMING_SNAKE_CASE ) __lowerCAmelCase : list[list[float]] = [ [random.randint(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for _ in range(SCREAMING_SNAKE_CASE )] for _ in range(SCREAMING_SNAKE_CASE ) ] return Matrix(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
232
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class snake_case_ ( __lowercase ): A_ = 'biogpt' def __init__( self : int , _snake_case : Any=42384 , _snake_case : Any=1024 , _snake_case : List[Any]=24 , _snake_case : Any=16 , _snake_case : List[str]=4096 , _snake_case : Dict="gelu" , _snake_case : Tuple=0.1 , _snake_case : str=0.1 , _snake_case : Tuple=1024 , _snake_case : Tuple=0.02 , _snake_case : Tuple=1E-12 , _snake_case : Optional[int]=True , _snake_case : Optional[int]=True , _snake_case : Any=0.0 , _snake_case : Tuple=0.0 , _snake_case : str=1 , _snake_case : Dict=0 , _snake_case : str=2 , **_snake_case : Union[str, Any] , )->Dict: '''simple docstring''' __lowerCAmelCase : List[Any] = vocab_size __lowerCAmelCase : Dict = max_position_embeddings __lowerCAmelCase : str = hidden_size __lowerCAmelCase : Dict = num_hidden_layers __lowerCAmelCase : List[Any] = num_attention_heads __lowerCAmelCase : Optional[Any] = intermediate_size __lowerCAmelCase : int = hidden_act __lowerCAmelCase : Any = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : Any = initializer_range __lowerCAmelCase : int = layer_norm_eps __lowerCAmelCase : Optional[int] = scale_embedding __lowerCAmelCase : List[Any] = use_cache __lowerCAmelCase : str = layerdrop __lowerCAmelCase : Dict = activation_dropout super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case )
232
1
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 __snake_case : def __init__( self ,snake_case ,snake_case=13 ,snake_case=7 ,snake_case=True ,snake_case=True ,snake_case=True ,snake_case=True ,snake_case=99 ,snake_case=16 ,snake_case=36 ,snake_case=6 ,snake_case=6 ,snake_case=6 ,snake_case=37 ,snake_case="gelu" ,snake_case=0.1 ,snake_case=0.1 ,snake_case=512 ,snake_case=16 ,snake_case=2 ,snake_case=0.02 ,snake_case=3 ,snake_case=4 ,snake_case=None ,): '''simple docstring''' lowercase : Union[str, Any] = parent lowercase : Dict = batch_size lowercase : Optional[int] = seq_length lowercase : Union[str, Any] = is_training lowercase : Dict = use_input_mask lowercase : Dict = use_token_type_ids lowercase : str = use_labels lowercase : Union[str, Any] = vocab_size lowercase : int = embedding_size lowercase : List[str] = hidden_size lowercase : Dict = num_hidden_layers lowercase : Optional[Any] = num_hidden_groups lowercase : List[Any] = num_attention_heads lowercase : Union[str, Any] = intermediate_size lowercase : Any = hidden_act lowercase : Tuple = hidden_dropout_prob lowercase : Dict = attention_probs_dropout_prob lowercase : Any = max_position_embeddings lowercase : List[str] = type_vocab_size lowercase : int = type_sequence_label_size lowercase : Optional[Any] = initializer_range lowercase : int = num_labels lowercase : Optional[Any] = num_choices lowercase : Union[str, Any] = scope def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowercase : Union[str, Any] = None if self.use_input_mask: lowercase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) lowercase : Optional[int] = None if self.use_token_type_ids: lowercase : Any = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) lowercase : Tuple = None lowercase : Any = None lowercase : Any = None if self.use_labels: lowercase : List[Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowercase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) lowercase : List[str] = ids_tensor([self.batch_size] ,self.num_choices ) lowercase : Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self ): '''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 _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : int = AlbertModel(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[str] = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ) lowercase : str = model(snake_case ,token_type_ids=snake_case ) lowercase : Optional[Any] = model(snake_case ) 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 _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Tuple = AlbertForPreTraining(config=snake_case ) model.to(snake_case ) model.eval() lowercase : Union[str, Any] = model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ,sentence_order_label=snake_case ,) 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 _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : int = AlbertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() lowercase : int = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : str = AlbertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[str] = model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,start_positions=snake_case ,end_positions=snake_case ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : str = self.num_labels lowercase : Tuple = AlbertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() lowercase : Tuple = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Tuple = self.num_labels lowercase : Optional[int] = AlbertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() lowercase : int = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Any = self.num_choices lowercase : Any = AlbertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[Any] = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowercase : Tuple = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowercase : Tuple = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowercase : Dict = model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) : str = config_and_inputs lowercase : int = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __snake_case ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): _a : Tuple= ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) _a : List[str]= ( { "feature-extraction": AlbertModel, "fill-mask": AlbertForMaskedLM, "question-answering": AlbertForQuestionAnswering, "text-classification": AlbertForSequenceClassification, "token-classification": AlbertForTokenClassification, "zero-shot": AlbertForSequenceClassification, } if is_torch_available() else {} ) _a : Dict= True def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case=False ): '''simple docstring''' lowercase : List[str] = super()._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) if return_labels: if model_class in get_values(snake_case ): lowercase : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) ,dtype=torch.long ,device=snake_case ) lowercase : str = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=snake_case ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = AlbertModelTester(self ) lowercase : Optional[int] = ConfigTester(self ,config_class=snake_case ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowercase : Optional[Any] = type self.model_tester.create_and_check_model(*snake_case ) @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : List[Any] = AlbertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_torch class __snake_case ( unittest.TestCase ): @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = AlbertModel.from_pretrained("""albert-base-v2""" ) lowercase : int = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) lowercase : Optional[int] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowercase : List[str] = model(snake_case ,attention_mask=snake_case )[0] lowercase : Any = torch.Size((1, 11, 768) ) self.assertEqual(output.shape ,snake_case ) lowercase : int = torch.tensor( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,snake_case ,atol=1e-4 ) )
20
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging lowercase : List[str] = logging.get_logger(__name__) lowercase : Optional[Any] = { """EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""", # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class __snake_case ( lowerCAmelCase ): _a : str= "gpt_neo" _a : Optional[int]= ["past_key_values"] _a : Dict= {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self ,snake_case=50257 ,snake_case=2048 ,snake_case=2048 ,snake_case=24 ,snake_case=[[["global", "local"], 12]] ,snake_case=16 ,snake_case=None ,snake_case=256 ,snake_case="gelu_new" ,snake_case=0.0 ,snake_case=0.0 ,snake_case=0.0 ,snake_case=0.1 ,snake_case=1e-5 ,snake_case=0.02 ,snake_case=True ,snake_case=50256 ,snake_case=50256 ,**snake_case ,): '''simple docstring''' lowercase : int = vocab_size lowercase : Union[str, Any] = max_position_embeddings lowercase : Dict = hidden_size lowercase : Union[str, Any] = num_layers lowercase : Union[str, Any] = num_heads lowercase : Optional[int] = intermediate_size lowercase : List[str] = window_size lowercase : Optional[int] = activation_function lowercase : List[str] = resid_dropout lowercase : int = embed_dropout lowercase : Optional[int] = attention_dropout lowercase : Tuple = classifier_dropout lowercase : Optional[int] = layer_norm_epsilon lowercase : Dict = initializer_range lowercase : List[str] = use_cache lowercase : Optional[int] = bos_token_id lowercase : int = eos_token_id lowercase : Union[str, Any] = attention_types lowercase : Dict = self.expand_attention_types_params(snake_case ) if len(self.attention_layers ) != self.num_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.attention_layers)` == `config.num_layers` """ f"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " f"`config.num_layers = {self.num_layers}`. " """`config.attention_layers` is prepared using `config.attention_types`. """ """Please verify the value of `config.attention_types` argument.""" ) super().__init__(bos_token_id=snake_case ,eos_token_id=snake_case ,**snake_case ) @staticmethod def _SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' lowercase : List[Any] = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Tuple: import torch lowercase : Tuple = input.size() lowercase : int = len(SCREAMING_SNAKE_CASE__ ) lowercase : Union[str, Any] = shape[dimension] lowercase : int = torch.arange(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : Optional[Any] = torch.div(sizedim - size , SCREAMING_SNAKE_CASE__ , rounding_mode="""floor""" ) + 1 lowercase : Dict = torch.arange(SCREAMING_SNAKE_CASE__ ) + low_indices[:min_length][:, None] lowercase : Union[str, Any] = [slice(SCREAMING_SNAKE_CASE__ )] * rank lowercase : Optional[Any] = indices lowercase : List[str] = input[s] lowercase : Optional[int] = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(SCREAMING_SNAKE_CASE__ ) def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: import torch lowercase : Union[str, Any] = torch.arange(1 , SCREAMING_SNAKE_CASE__ ) lowercase : Optional[Any] = torch.remainder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = remainders == 0 lowercase : Optional[int] = candidates[divisor_indices] lowercase : List[Any] = torch.max(SCREAMING_SNAKE_CASE__ ) return largest_divisor, torch.div(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , rounding_mode="""floor""" ) class __snake_case ( lowerCAmelCase ): @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(snake_case ,direction="""inputs""" ) lowercase : Dict = {0: """batch""", 1: """past_sequence + sequence"""} else: lowercase : List[str] = {0: """batch""", 1: """sequence"""} return common_inputs @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return self._config.num_heads def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case = -1 ,snake_case = -1 ,snake_case = False ,snake_case = None ,): '''simple docstring''' lowercase : Any = super(snake_case ,self ).generate_dummy_inputs( snake_case ,batch_size=snake_case ,seq_length=snake_case ,is_pair=snake_case ,framework=snake_case ) # We need to order the input in the way they appears in the forward() lowercase : List[str] = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch lowercase , lowercase : List[Any] = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values lowercase : Optional[int] = seqlen + 2 lowercase : int = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowercase : Optional[Any] = [ (torch.zeros(snake_case ), torch.zeros(snake_case )) for _ in range(self.num_layers ) ] lowercase : Optional[Any] = common_inputs["""attention_mask"""] if self.use_past: lowercase : Any = ordered_inputs["""attention_mask"""].dtype lowercase : Union[str, Any] = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(snake_case ,snake_case ,dtype=snake_case )] ,dim=1 ) return ordered_inputs @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return 13
20
1
'''simple docstring''' from math import factorial def a_ ( lowerCamelCase : int = 100 ): return sum(map(lowerCamelCase , str(factorial(lowerCamelCase ) ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
55
'''simple docstring''' import math def a_ ( lowerCamelCase : int ): lowerCAmelCase = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCamelCase ) def a_ ( lowerCamelCase : float = 1 / 12345 ): lowerCAmelCase = 0 lowerCAmelCase = 0 lowerCAmelCase = 3 while True: lowerCAmelCase = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCamelCase ): lowerCAmelCase = int(lowerCamelCase ) total_partitions += 1 if check_partition_perfect(lowerCamelCase ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCamelCase ) integer += 1 if __name__ == "__main__": print(F'''{solution() = }''')
55
1
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Union[str, Any] ): UpperCamelCase :Union[str, Any] = """ylacombe/bark-small""" UpperCamelCase :List[str] = tempfile.mkdtemp() UpperCamelCase :List[Any] = """en_speaker_1""" UpperCamelCase :int = """This is a test string""" UpperCamelCase :int = """speaker_embeddings_path.json""" UpperCamelCase :Optional[Any] = """speaker_embeddings""" def _A ( self : int , **__lowerCamelCase : Any ): return AutoTokenizer.from_pretrained(self.checkpoint , **__lowerCamelCase ) def _A ( self : Dict ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.get_tokenizer() UpperCamelCase :str = BarkProcessor(tokenizer=__lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase :Union[str, Any] = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def _A ( self : int ): UpperCamelCase :Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) UpperCamelCase :Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCamelCase :Tuple = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def _A ( self : Tuple ): UpperCamelCase :Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) UpperCamelCase :Any = 35 UpperCamelCase :Optional[int] = 2 UpperCamelCase :Tuple = 8 UpperCamelCase :Optional[Any] = { """semantic_prompt""": np.ones(__lowerCamelCase ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset UpperCamelCase :List[Any] = processor(text=self.input_string , voice_preset=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file UpperCamelCase :List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(__lowerCamelCase , **__lowerCamelCase ) UpperCamelCase :Tuple = processor(text=self.input_string , voice_preset=__lowerCamelCase ) UpperCamelCase :Dict = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub UpperCamelCase :List[Any] = processor(text=self.input_string , voice_preset=self.voice_preset ) def _A ( self : List[str] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = BarkProcessor(tokenizer=__lowerCamelCase ) UpperCamelCase :Tuple = processor(text=self.input_string ) UpperCamelCase :Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
38
from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput __UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" @register_to_config def __init__( self , _A , _A = None , _A = None ) -> Optional[Any]: super().__init__() SCREAMING_SNAKE_CASE_ = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" SCREAMING_SNAKE_CASE_ = torch.zeros(_A , _A ) else: SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(_A ) class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCAmelCase_ =42 UpperCAmelCase_ =42 UpperCAmelCase_ =42 UpperCAmelCase_ =42 UpperCAmelCase_ =42 UpperCAmelCase_ =42 def __init__( self , _A , _A , _A , _A , _A , _A , ) -> Any: super().__init__() self.register_modules( vqvae=_A , transformer=_A , text_encoder=_A , tokenizer=_A , scheduler=_A , learned_classifier_free_sampling_embeddings=_A , ) def _UpperCamelCase ( self , _A , _A , _A ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = len(_A ) if isinstance(_A , _A ) else 1 # get prompt text embeddings SCREAMING_SNAKE_CASE_ = self.tokenizer( _A , padding='''max_length''' , max_length=self.tokenizer.model_max_length , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) SCREAMING_SNAKE_CASE_ = text_input_ids[:, : self.tokenizer.model_max_length] SCREAMING_SNAKE_CASE_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 SCREAMING_SNAKE_CASE_ = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=_A ) # duplicate text embeddings for each generation per prompt SCREAMING_SNAKE_CASE_ = prompt_embeds.repeat_interleave(_A , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: SCREAMING_SNAKE_CASE_ = self.learned_classifier_free_sampling_embeddings.embeddings SCREAMING_SNAKE_CASE_ = negative_prompt_embeds.unsqueeze(0 ).repeat(_A , 1 , 1 ) else: SCREAMING_SNAKE_CASE_ = [''''''] * batch_size SCREAMING_SNAKE_CASE_ = text_input_ids.shape[-1] SCREAMING_SNAKE_CASE_ = self.tokenizer( _A , padding='''max_length''' , max_length=_A , truncation=_A , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings SCREAMING_SNAKE_CASE_ = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=_A ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE_ = negative_prompt_embeds.shape[1] SCREAMING_SNAKE_CASE_ = negative_prompt_embeds.repeat(1 , _A , 1 ) SCREAMING_SNAKE_CASE_ = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _A , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes SCREAMING_SNAKE_CASE_ = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self , _A , _A = 100 , _A = 5.0 , _A = 1.0 , _A = 1 , _A = None , _A = None , _A = "pil" , _A = True , _A = None , _A = 1 , ) -> Union[ImagePipelineOutput, Tuple]: if isinstance(_A , _A ): SCREAMING_SNAKE_CASE_ = 1 elif isinstance(_A , _A ): SCREAMING_SNAKE_CASE_ = len(_A ) else: raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(_A )}''' ) SCREAMING_SNAKE_CASE_ = batch_size * num_images_per_prompt SCREAMING_SNAKE_CASE_ = guidance_scale > 1.0 SCREAMING_SNAKE_CASE_ = self._encode_prompt(_A , _A , _A ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(_A , _A ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(_A )}.''' ) # get the initial completely masked latents unless the user supplied it SCREAMING_SNAKE_CASE_ = (batch_size, self.transformer.num_latent_pixels) if latents is None: SCREAMING_SNAKE_CASE_ = self.transformer.num_vector_embeds - 1 SCREAMING_SNAKE_CASE_ = torch.full(_A , _A ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( '''Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,''' F''' {self.transformer.num_vector_embeds - 1} (inclusive).''' ) SCREAMING_SNAKE_CASE_ = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(_A , device=self.device ) SCREAMING_SNAKE_CASE_ = self.scheduler.timesteps.to(self.device ) SCREAMING_SNAKE_CASE_ = latents for i, t in enumerate(self.progress_bar(_A ) ): # expand the sample if we are doing classifier free guidance SCREAMING_SNAKE_CASE_ = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` SCREAMING_SNAKE_CASE_ = self.transformer(_A , encoder_hidden_states=_A , timestep=_A ).sample if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model_output.chunk(2 ) SCREAMING_SNAKE_CASE_ = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(_A , dim=1 , keepdim=_A ) SCREAMING_SNAKE_CASE_ = self.truncate(_A , _A ) # remove `log(0)`'s (`-inf`s) SCREAMING_SNAKE_CASE_ = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE_ = self.scheduler.step(_A , timestep=_A , sample=_A , generator=_A ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(_A , _A , _A ) SCREAMING_SNAKE_CASE_ = self.vqvae.config.vq_embed_dim SCREAMING_SNAKE_CASE_ = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) SCREAMING_SNAKE_CASE_ = self.vqvae.quantize.get_codebook_entry(_A , shape=_A ) SCREAMING_SNAKE_CASE_ = self.vqvae.decode(_A , force_not_quantize=_A ).sample SCREAMING_SNAKE_CASE_ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A ) def _UpperCamelCase ( self , _A , _A ) -> torch.FloatTensor: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.sort(_A , 1 , descending=_A ) SCREAMING_SNAKE_CASE_ = torch.exp(_A ) SCREAMING_SNAKE_CASE_ = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out SCREAMING_SNAKE_CASE_ = torch.full_like(keep_mask[:, 0:1, :] , _A ) SCREAMING_SNAKE_CASE_ = torch.cat((all_true, keep_mask) , dim=1 ) SCREAMING_SNAKE_CASE_ = keep_mask[:, :-1, :] SCREAMING_SNAKE_CASE_ = keep_mask.gather(1 , indices.argsort(1 ) ) SCREAMING_SNAKE_CASE_ = log_p_x_0.clone() SCREAMING_SNAKE_CASE_ = -torch.inf # -inf = log(0) return rv
299
0
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class a ( UpperCAmelCase ): _lowercase = (DDPMScheduler,) def _UpperCAmelCase ( self , **A_ ): '''simple docstring''' _UpperCAmelCase : List[str] = { "num_train_timesteps": 1000, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", "variance_type": "fixed_small", "clip_sample": True, } config.update(**A_ ) return config def _UpperCAmelCase ( self ): '''simple docstring''' for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=A_ , beta_end=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' self.check_over_configs(thresholding=A_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=A_ , prediction_type=A_ , sample_max_value=A_ , ) def _UpperCAmelCase ( self ): '''simple docstring''' for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for t in [0, 500, 999]: self.check_over_forward(time_step=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Any = self.scheduler_classes[0] _UpperCAmelCase : Any = self.get_scheduler_config() _UpperCAmelCase : List[Any] = scheduler_class(**A_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1e-5 def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] = self.scheduler_classes[0] _UpperCAmelCase : str = self.get_scheduler_config() _UpperCAmelCase : Optional[Any] = scheduler_class(**A_ ) _UpperCAmelCase : List[Any] = len(A_ ) _UpperCAmelCase : Union[str, Any] = self.dummy_model() _UpperCAmelCase : str = self.dummy_sample_deter _UpperCAmelCase : Dict = torch.manual_seed(0 ) for t in reversed(range(A_ ) ): # 1. predict noise residual _UpperCAmelCase : str = model(A_ , A_ ) # 2. predict previous mean of sample x_t-1 _UpperCAmelCase : str = scheduler.step(A_ , A_ , A_ , generator=A_ ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _UpperCAmelCase : Dict = pred_prev_sample _UpperCAmelCase : Any = torch.sum(torch.abs(A_ ) ) _UpperCAmelCase : Optional[Any] = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 258.9606 ) < 1e-2 assert abs(result_mean.item() - 0.33_72 ) < 1e-3 def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Dict = self.scheduler_classes[0] _UpperCAmelCase : Dict = self.get_scheduler_config(prediction_type="v_prediction" ) _UpperCAmelCase : Optional[Any] = scheduler_class(**A_ ) _UpperCAmelCase : Optional[Any] = len(A_ ) _UpperCAmelCase : Optional[Any] = self.dummy_model() _UpperCAmelCase : Tuple = self.dummy_sample_deter _UpperCAmelCase : List[Any] = torch.manual_seed(0 ) for t in reversed(range(A_ ) ): # 1. predict noise residual _UpperCAmelCase : List[str] = model(A_ , A_ ) # 2. predict previous mean of sample x_t-1 _UpperCAmelCase : int = scheduler.step(A_ , A_ , A_ , generator=A_ ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _UpperCAmelCase : List[Any] = pred_prev_sample _UpperCAmelCase : Union[str, Any] = torch.sum(torch.abs(A_ ) ) _UpperCAmelCase : int = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 202.0296 ) < 1e-2 assert abs(result_mean.item() - 0.26_31 ) < 1e-3 def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Any = self.scheduler_classes[0] _UpperCAmelCase : Optional[Any] = self.get_scheduler_config() _UpperCAmelCase : Optional[int] = scheduler_class(**A_ ) _UpperCAmelCase : Any = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=A_ ) _UpperCAmelCase : str = scheduler.timesteps for i, timestep in enumerate(A_ ): if i == len(A_ ) - 1: _UpperCAmelCase : str = -1 else: _UpperCAmelCase : Tuple = timesteps[i + 1] _UpperCAmelCase : str = scheduler.previous_timestep(A_ ) _UpperCAmelCase : Union[str, Any] = prev_t.item() self.assertEqual(A_ , A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : str = self.scheduler_classes[0] _UpperCAmelCase : str = self.get_scheduler_config() _UpperCAmelCase : List[str] = scheduler_class(**A_ ) _UpperCAmelCase : Union[str, Any] = [100, 87, 50, 51, 0] with self.assertRaises(A_ , msg="`custom_timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : List[Any] = self.scheduler_classes[0] _UpperCAmelCase : int = self.get_scheduler_config() _UpperCAmelCase : Union[str, Any] = scheduler_class(**A_ ) _UpperCAmelCase : str = [100, 87, 50, 1, 0] _UpperCAmelCase : str = len(A_ ) with self.assertRaises(A_ , msg="Can only pass one of `num_inference_steps` or `custom_timesteps`." ): scheduler.set_timesteps(num_inference_steps=A_ , timesteps=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : str = self.scheduler_classes[0] _UpperCAmelCase : Dict = self.get_scheduler_config() _UpperCAmelCase : int = scheduler_class(**A_ ) _UpperCAmelCase : str = [scheduler.config.num_train_timesteps] with self.assertRaises( A_ , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=A_ )
363
import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class a ( UpperCAmelCase ): def __get__( self , A_ , A_=None ): '''simple docstring''' if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute" ) _UpperCAmelCase : Optional[int] = "__cached_" + self.fget.__name__ _UpperCAmelCase : Union[str, Any] = getattr(A_ , A_ , A_ ) if cached is None: _UpperCAmelCase : Dict = self.fget(A_ ) setattr(A_ , A_ , A_ ) return cached def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> int: _UpperCAmelCase : str = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(F'invalid truth value {val!r}' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> int: if is_torch_fx_proxy(lowerCAmelCase ): return True if is_torch_available(): import torch if isinstance(lowerCAmelCase , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(lowerCAmelCase , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(lowerCAmelCase , (jnp.ndarray, Tracer) ): return True return isinstance(lowerCAmelCase , np.ndarray ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> Dict: return isinstance(lowerCAmelCase , np.ndarray ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> Any: return _is_numpy(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Tuple ) -> Optional[int]: import torch return isinstance(lowerCAmelCase , torch.Tensor ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> Optional[int]: return False if not is_torch_available() else _is_torch(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> List[Any]: import torch return isinstance(lowerCAmelCase , torch.device ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: int ) -> Tuple: return False if not is_torch_available() else _is_torch_device(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] ) -> Tuple: import torch if isinstance(lowerCAmelCase , lowerCAmelCase ): if hasattr(lowerCAmelCase , lowerCAmelCase ): _UpperCAmelCase : Any = getattr(lowerCAmelCase , lowerCAmelCase ) else: return False return isinstance(lowerCAmelCase , torch.dtype ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> int: return False if not is_torch_available() else _is_torch_dtype(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> Optional[Any]: import tensorflow as tf return isinstance(lowerCAmelCase , tf.Tensor ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str ) -> Optional[Any]: return False if not is_tf_available() else _is_tensorflow(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[int] ) -> Any: import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(lowerCAmelCase , "is_symbolic_tensor" ): return tf.is_symbolic_tensor(lowerCAmelCase ) return type(lowerCAmelCase ) == tf.Tensor def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Tuple ) -> Optional[Any]: return False if not is_tf_available() else _is_tf_symbolic_tensor(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> List[str]: import jax.numpy as jnp # noqa: F811 return isinstance(lowerCAmelCase , jnp.ndarray ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> str: return False if not is_flax_available() else _is_jax(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str ) -> Tuple: if isinstance(lowerCAmelCase , (dict, UserDict) ): return {k: to_py_obj(lowerCAmelCase ) for k, v in obj.items()} elif isinstance(lowerCAmelCase , (list, tuple) ): return [to_py_obj(lowerCAmelCase ) for o in obj] elif is_tf_tensor(lowerCAmelCase ): return obj.numpy().tolist() elif is_torch_tensor(lowerCAmelCase ): return obj.detach().cpu().tolist() elif is_jax_tensor(lowerCAmelCase ): return np.asarray(lowerCAmelCase ).tolist() elif isinstance(lowerCAmelCase , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> List[Any]: if isinstance(lowerCAmelCase , (dict, UserDict) ): return {k: to_numpy(lowerCAmelCase ) for k, v in obj.items()} elif isinstance(lowerCAmelCase , (list, tuple) ): return np.array(lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): return obj.numpy() elif is_torch_tensor(lowerCAmelCase ): return obj.detach().cpu().numpy() elif is_jax_tensor(lowerCAmelCase ): return np.asarray(lowerCAmelCase ) else: return obj class a ( UpperCAmelCase ): def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Optional[Any] = fields(self ) # Safety and consistency checks if not len(A_ ): raise ValueError(f'{self.__class__.__name__} has no fields.' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'{self.__class__.__name__} should not have more than one required field.' ) _UpperCAmelCase : Any = getattr(self , class_fields[0].name ) _UpperCAmelCase : List[str] = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(A_ ): if isinstance(A_ , A_ ): _UpperCAmelCase : Union[str, Any] = first_field.items() _UpperCAmelCase : Optional[int] = True else: try: _UpperCAmelCase : Tuple = iter(A_ ) _UpperCAmelCase : Any = True except TypeError: _UpperCAmelCase : str = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(A_ ): if ( not isinstance(A_ , (list, tuple) ) or not len(A_ ) == 2 or not isinstance(element[0] , A_ ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute _UpperCAmelCase : str = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'Cannot set key/value for {element}. It needs to be a tuple (key, value).' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: _UpperCAmelCase : List[str] = element[1] elif first_field is not None: _UpperCAmelCase : Tuple = first_field else: for field in class_fields: _UpperCAmelCase : int = getattr(self , field.name ) if v is not None: _UpperCAmelCase : Union[str, Any] = v def __delitem__( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.' ) def _UpperCAmelCase ( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.' ) def _UpperCAmelCase ( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``pop`` on a {self.__class__.__name__} instance.' ) def _UpperCAmelCase ( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``update`` on a {self.__class__.__name__} instance.' ) def __getitem__( self , A_ ): '''simple docstring''' if isinstance(A_ , A_ ): _UpperCAmelCase : Optional[int] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self , A_ , A_ ): '''simple docstring''' if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(A_ , A_ ) super().__setattr__(A_ , A_ ) def __setitem__( self , A_ , A_ ): '''simple docstring''' super().__setitem__(A_ , A_ ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(A_ , A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' return tuple(self[k] for k in self.keys() ) class a ( UpperCAmelCase , UpperCAmelCase ): @classmethod def _UpperCAmelCase ( cls , A_ ): '''simple docstring''' raise ValueError( f'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}' ) class a ( UpperCAmelCase ): _lowercase = "longest" _lowercase = "max_length" _lowercase = "do_not_pad" class a ( UpperCAmelCase ): _lowercase = "pt" _lowercase = "tf" _lowercase = "np" _lowercase = "jax" class a : def __init__( self , A_ ): '''simple docstring''' _UpperCAmelCase : Tuple = context_managers _UpperCAmelCase : Dict = ExitStack() def __enter__( self ): '''simple docstring''' for context_manager in self.context_managers: self.stack.enter_context(A_ ) def __exit__( self , *A_ , **A_ ): '''simple docstring''' self.stack.__exit__(*A_ , **A_ ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: int ) -> Optional[Any]: _UpperCAmelCase : Optional[Any] = infer_framework(lowerCAmelCase ) if framework == "tf": _UpperCAmelCase : Union[str, Any] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _UpperCAmelCase : Optional[int] = inspect.signature(model_class.forward ) # PyTorch models else: _UpperCAmelCase : Dict = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] ) -> List[str]: _UpperCAmelCase : List[Any] = model_class.__name__ _UpperCAmelCase : Dict = infer_framework(lowerCAmelCase ) if framework == "tf": _UpperCAmelCase : Dict = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _UpperCAmelCase : Dict = inspect.signature(model_class.forward ) # PyTorch models else: _UpperCAmelCase : Tuple = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: MutableMapping , lowerCAmelCase: str = "" , lowerCAmelCase: str = "." ) -> List[Any]: def _flatten_dict(lowerCAmelCase: int , lowerCAmelCase: Tuple="" , lowerCAmelCase: List[str]="." ): for k, v in d.items(): _UpperCAmelCase : Optional[int] = str(lowerCAmelCase ) + delimiter + str(lowerCAmelCase ) if parent_key else k if v and isinstance(lowerCAmelCase , lowerCAmelCase ): yield from flatten_dict(lowerCAmelCase , lowerCAmelCase , delimiter=lowerCAmelCase ).items() else: yield key, v return dict(_flatten_dict(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) ) @contextmanager def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Union[str, Any] , lowerCAmelCase: bool = False ) -> List[Any]: if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Dict , lowerCAmelCase: Tuple=None ) -> List[str]: if is_numpy_array(lowerCAmelCase ): return np.transpose(lowerCAmelCase , axes=lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.T if axes is None else array.permute(*lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.transpose(lowerCAmelCase , perm=lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.transpose(lowerCAmelCase , axes=lowerCAmelCase ) else: raise ValueError(F'Type not supported for transpose: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] , lowerCAmelCase: Any ) -> int: if is_numpy_array(lowerCAmelCase ): return np.reshape(lowerCAmelCase , lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.reshape(*lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.reshape(lowerCAmelCase , lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.reshape(lowerCAmelCase , lowerCAmelCase ) else: raise ValueError(F'Type not supported for reshape: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str , lowerCAmelCase: Union[str, Any]=None ) -> Union[str, Any]: if is_numpy_array(lowerCAmelCase ): return np.squeeze(lowerCAmelCase , axis=lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.squeeze() if axis is None else array.squeeze(dim=lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.squeeze(lowerCAmelCase , axis=lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.squeeze(lowerCAmelCase , axis=lowerCAmelCase ) else: raise ValueError(F'Type not supported for squeeze: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Dict , lowerCAmelCase: List[str] ) -> Union[str, Any]: if is_numpy_array(lowerCAmelCase ): return np.expand_dims(lowerCAmelCase , lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.unsqueeze(dim=lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.expand_dims(lowerCAmelCase , axis=lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.expand_dims(lowerCAmelCase , axis=lowerCAmelCase ) else: raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> int: if is_numpy_array(lowerCAmelCase ): return np.size(lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.numel() elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.size(lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return array.size else: raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] , lowerCAmelCase: List[Any] ) -> List[Any]: for key, value in auto_map.items(): if isinstance(lowerCAmelCase , (tuple, list) ): _UpperCAmelCase : List[Any] = [F'{repo_id}--{v}' if (v is not None and "--" not in v) else v for v in value] elif value is not None and "--" not in value: _UpperCAmelCase : Tuple = F'{repo_id}--{value}' return auto_map def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> List[Any]: for base_class in inspect.getmro(lowerCAmelCase ): _UpperCAmelCase : int = base_class.__module__ _UpperCAmelCase : Dict = base_class.__name__ if module.startswith("tensorflow" ) or module.startswith("keras" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("torch" ) or name == "PreTrainedModel": return "pt" elif module.startswith("flax" ) or module.startswith("jax" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(F'Could not infer framework from class {model_class}.' )
189
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, unittest.TestCase ): __lowerCAmelCase = StableUnCLIPImgaImgPipeline __lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS __lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __lowerCAmelCase = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __lowerCAmelCase = frozenset([] ) def __magic_name__ ( self ): lowercase : Tuple = 32 lowercase : Optional[int] = embedder_hidden_size # image encoding components lowercase : Union[str, Any] = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) lowercase : Union[str, Any] = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__lowercase , projection_dim=__lowercase , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) lowercase : str = StableUnCLIPImageNormalizer(embedding_dim=__lowercase ) lowercase : Optional[int] = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) lowercase : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) lowercase : Dict = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__lowercase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) ) torch.manual_seed(0 ) lowercase : List[Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__lowercase , layers_per_block=1 , upcast_attention=__lowercase , use_linear_projection=__lowercase , ) torch.manual_seed(0 ) lowercase : Tuple = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type="v_prediction" , set_alpha_to_one=__lowercase , steps_offset=1 , ) torch.manual_seed(0 ) lowercase : List[str] = AutoencoderKL() lowercase : Tuple = { # image encoding components '''feature_extractor''': feature_extractor, '''image_encoder''': image_encoder.eval(), # image noising components '''image_normalizer''': image_normalizer.eval(), '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder.eval(), '''unet''': unet.eval(), '''scheduler''': scheduler, '''vae''': vae.eval(), } return components def __magic_name__ ( self , _a , _a=0 , _a=True ): if str(__lowercase ).startswith("mps" ): lowercase : Union[str, Any] = torch.manual_seed(__lowercase ) else: lowercase : int = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) lowercase : int = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowercase ) ).to(__lowercase ) if pil_image: lowercase : List[Any] = input_image * 0.5 + 0.5 lowercase : Optional[Any] = input_image.clamp(0 , 1 ) lowercase : int = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() lowercase : Optional[Any] = DiffusionPipeline.numpy_to_pil(__lowercase )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def __magic_name__ ( self ): lowercase : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowercase : Tuple = self.get_dummy_components() lowercase : Any = StableUnCLIPImgaImgPipeline(**__lowercase ) lowercase : Optional[Any] = sd_pipe.to(__lowercase ) sd_pipe.set_progress_bar_config(disable=__lowercase ) lowercase : List[Any] = self.get_dummy_inputs(__lowercase ) inputs.update({"image_embeds": None} ) lowercase : Any = sd_pipe(**__lowercase ).images lowercase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowercase : List[Any] = np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def __magic_name__ ( self ): lowercase : Optional[Any] = torch_device in ['''cpu''', '''mps'''] self._test_attention_slicing_forward_pass(test_max_difference=__lowercase ) def __magic_name__ ( self ): lowercase : Optional[Any] = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=__lowercase ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __magic_name__ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__lowercase ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __magic_name__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self ): lowercase : int = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) lowercase : Any = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy" ) lowercase : List[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-l-img2img" , torch_dtype=torch.floataa ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() lowercase : int = torch.Generator(device="cpu" ).manual_seed(0 ) lowercase : Dict = pipe(__lowercase , "anime turle" , generator=__lowercase , output_type="np" ) lowercase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__lowercase , __lowercase ) def __magic_name__ ( self ): lowercase : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) lowercase : Any = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy" ) lowercase : Any = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() lowercase : int = torch.Generator(device="cpu" ).manual_seed(0 ) lowercase : Optional[int] = pipe(__lowercase , "anime turle" , generator=__lowercase , output_type="np" ) lowercase : List[Any] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__lowercase , __lowercase ) def __magic_name__ ( self ): lowercase : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowercase : List[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) lowercase : Union[str, Any] = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() lowercase : Optional[Any] = pipe( __lowercase , "anime turtle" , num_inference_steps=2 , output_type="np" , ) lowercase : int = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
202
def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Tuple = [0 for i in range(len(SCREAMING_SNAKE_CASE ) )] # initialize interval's left pointer and right pointer __UpperCamelCase , __UpperCamelCase :str = 0, 0 for i in range(1 , len(SCREAMING_SNAKE_CASE ) ): # case when current index is inside the interval if i <= right_pointer: __UpperCamelCase :Union[str, Any] = min(right_pointer - i + 1 , z_result[i - left_pointer] ) __UpperCamelCase :Tuple = min_edge while go_next(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: __UpperCamelCase , __UpperCamelCase :Union[str, Any] = i, i + z_result[i] - 1 return z_result def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' return i + z_result[i] < len(SCREAMING_SNAKE_CASE ) and s[z_result[i]] == s[i + z_result[i]] def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :List[Any] = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string __UpperCamelCase :Tuple = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(SCREAMING_SNAKE_CASE ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
43
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = {'configuration_mmbt': ['MMBTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = ['MMBTForClassification', 'MMBTModel', 'ModalEmbeddings'] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
356
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() __a = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) __a = [] 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__ ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' UpperCAmelCase_ : int = state_dict.pop(_lowercase ) UpperCAmelCase_ : Optional[int] = val def lowerCamelCase__ ( _lowercase ): '''simple docstring''' UpperCAmelCase_ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: UpperCAmelCase_ : List[Any] = key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) UpperCAmelCase_ : Optional[Any] = value else: UpperCAmelCase_ : Union[str, Any] = value return new_state_dict def lowerCamelCase__ ( _lowercase ): '''simple docstring''' UpperCAmelCase_ : int = '''''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) UpperCAmelCase_ : Dict = state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) UpperCAmelCase_ : Any = state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ : Union[str, Any] = in_proj_weight[:256, :] UpperCAmelCase_ : Optional[int] = in_proj_bias[:256] UpperCAmelCase_ : Tuple = in_proj_weight[256:512, :] UpperCAmelCase_ : List[Any] = in_proj_bias[256:512] UpperCAmelCase_ : Union[str, Any] = in_proj_weight[-256:, :] UpperCAmelCase_ : str = 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 UpperCAmelCase_ : Any = state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) UpperCAmelCase_ : Optional[int] = state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ : Union[str, Any] = in_proj_weight[:256, :] UpperCAmelCase_ : List[str] = in_proj_bias[:256] UpperCAmelCase_ : Optional[int] = in_proj_weight[256:512, :] UpperCAmelCase_ : str = in_proj_bias[256:512] UpperCAmelCase_ : Optional[Any] = in_proj_weight[-256:, :] UpperCAmelCase_ : Union[str, Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention UpperCAmelCase_ : List[str] = state_dict.pop( f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) UpperCAmelCase_ : List[Any] = state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict UpperCAmelCase_ : List[str] = in_proj_weight_cross_attn[:256, :] UpperCAmelCase_ : str = in_proj_bias_cross_attn[:256] UpperCAmelCase_ : int = in_proj_weight_cross_attn[256:512, :] UpperCAmelCase_ : Tuple = in_proj_bias_cross_attn[256:512] UpperCAmelCase_ : List[str] = in_proj_weight_cross_attn[-256:, :] UpperCAmelCase_ : Dict = in_proj_bias_cross_attn[-256:] def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' UpperCAmelCase_, UpperCAmelCase_ : List[Any] = image.size UpperCAmelCase_ : List[Any] = max(_lowercase , _lowercase ) UpperCAmelCase_ : Dict = 800 if '''detection''' in checkpoint_url else 1000 UpperCAmelCase_ : Any = target_max_size / current_max_size UpperCAmelCase_ : Any = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def lowerCamelCase__ ( _lowercase ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = F.to_tensor(_lowercase ) UpperCAmelCase_ : Optional[Any] = F.normalize(_lowercase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def lowerCamelCase__ ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' logger.info('''Converting model...''' ) # load original state dict UpperCAmelCase_ : Any = torch.hub.load_state_dict_from_url(_lowercase , map_location='''cpu''' ) # rename keys for src, dest in rename_keys: rename_key(_lowercase , _lowercase , _lowercase ) UpperCAmelCase_ : Optional[int] = rename_backbone_keys(_lowercase ) # query, key and value matrices need special treatment read_in_q_k_v(_lowercase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them UpperCAmelCase_ : int = '''model.''' for key in state_dict.copy().keys(): if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): UpperCAmelCase_ : int = state_dict.pop(_lowercase ) UpperCAmelCase_ : Dict = val # create HuggingFace model and load state dict UpperCAmelCase_ : str = TableTransformerConfig( backbone='''resnet18''' , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: UpperCAmelCase_ : Any = 15 UpperCAmelCase_ : List[str] = 2 UpperCAmelCase_ : Union[str, Any] = {0: '''table''', 1: '''table rotated'''} UpperCAmelCase_ : str = idalabel UpperCAmelCase_ : Optional[int] = {v: k for k, v in idalabel.items()} else: UpperCAmelCase_ : Optional[Any] = 125 UpperCAmelCase_ : Optional[Any] = 6 UpperCAmelCase_ : Dict = { 0: '''table''', 1: '''table column''', 2: '''table row''', 3: '''table column header''', 4: '''table projected row header''', 5: '''table spanning cell''', } UpperCAmelCase_ : Optional[Any] = idalabel UpperCAmelCase_ : Optional[int] = {v: k for k, v in idalabel.items()} UpperCAmelCase_ : Union[str, Any] = DetrImageProcessor( format='''coco_detection''' , max_size=800 if '''detection''' in checkpoint_url else 1000 ) UpperCAmelCase_ : Union[str, Any] = TableTransformerForObjectDetection(_lowercase ) model.load_state_dict(_lowercase ) model.eval() # verify our conversion UpperCAmelCase_ : str = '''example_pdf.png''' if '''detection''' in checkpoint_url else '''example_table.png''' UpperCAmelCase_ : Dict = hf_hub_download(repo_id='''nielsr/example-pdf''' , repo_type='''dataset''' , filename=_lowercase ) UpperCAmelCase_ : Dict = Image.open(_lowercase ).convert('''RGB''' ) UpperCAmelCase_ : Any = normalize(resize(_lowercase , _lowercase ) ).unsqueeze(0 ) UpperCAmelCase_ : Dict = model(_lowercase ) if "detection" in checkpoint_url: UpperCAmelCase_ : Any = (1, 15, 3) UpperCAmelCase_ : Optional[int] = torch.tensor( [[-6.7897, -16.9985, 6.7937], [-8.0186, -22.2192, 6.9677], [-7.3117, -21.0708, 7.4055]] ) UpperCAmelCase_ : Any = torch.tensor([[0.4867, 0.1767, 0.6732], [0.6718, 0.4479, 0.3830], [0.4716, 0.1760, 0.6364]] ) else: UpperCAmelCase_ : Any = (1, 125, 7) UpperCAmelCase_ : Any = torch.tensor( [[-18.1430, -8.3214, 4.8274], [-18.4685, -7.1361, -4.2667], [-26.3693, -9.3429, -4.9962]] ) UpperCAmelCase_ : str = torch.tensor([[0.4983, 0.5595, 0.9440], [0.4916, 0.6315, 0.5954], [0.6108, 0.8637, 0.1135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , _lowercase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , _lowercase , 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(_lowercase ).mkdir(exist_ok=_lowercase ) model.save_pretrained(_lowercase ) image_processor.save_pretrained(_lowercase ) if push_to_hub: # Push model to HF hub logger.info('''Pushing model to the hub...''' ) UpperCAmelCase_ : List[Any] = ( '''microsoft/table-transformer-detection''' if '''detection''' in checkpoint_url else '''microsoft/table-transformer-structure-recognition''' ) model.push_to_hub(_lowercase ) image_processor.push_to_hub(_lowercase ) if __name__ == "__main__": __a = 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.' ) __a = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
235
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case_ : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Optional[Any] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Union[str, Any] = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys snake_case_ : str = _LazyModule(__name__, globals()["__file__"], _import_structure)
125
'''simple docstring''' from math import factorial def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError('''Please enter positive integers for n and k where n >= k''' ) return factorial(SCREAMING_SNAKE_CASE__ ) // (factorial(SCREAMING_SNAKE_CASE__ ) * factorial(n - k )) if __name__ == "__main__": print( "The number of five-card hands possible from a standard", f'''fifty-two card deck is: {combinations(52, 5)}\n''', ) print( "If a class of 40 students must be arranged into groups of", f'''4 for group projects, there are {combinations(40, 4)} ways''', "to arrange them.\n", ) print( "If 10 teams are competing in a Formula One race, there", f'''are {combinations(10, 3)} ways that first, second and''', "third place can be awarded.", )
125
1
"""simple docstring""" import json import os import unittest from typing import Tuple from transformers import WavaVecaPhonemeCTCTokenizer from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput from transformers.testing_utils import require_phonemizer from ...test_tokenization_common import TokenizerTesterMixin @require_phonemizer class __UpperCamelCase ( _A , unittest.TestCase ): SCREAMING_SNAKE_CASE = WavaVecaPhonemeCTCTokenizer SCREAMING_SNAKE_CASE = False def SCREAMING_SNAKE_CASE__ (self : Tuple): super().setUp() A = ( "<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː " "ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː " "ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 " "oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ " "pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ " "yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ " "əʊ S ɡʲ onɡ2 u\" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ " "ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ " "ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ " "uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ " "ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ " "ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ " "ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4" ).split(" ") A = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE)))) A = {"pad_token": "<pad>", "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>"} A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"]) with open(self.vocab_file , "w" , encoding="utf-8") as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE) + "\n") def SCREAMING_SNAKE_CASE__ (self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[Any]=2_0 , __SCREAMING_SNAKE_CASE : Any=5): A = [(i, tokenizer.decode([i] , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE)) for i in range(len(__SCREAMING_SNAKE_CASE))] A = list(filter(lambda __SCREAMING_SNAKE_CASE: [t[0]] == tokenizer.encode(t[1] , do_phonemize=__SCREAMING_SNAKE_CASE) , __SCREAMING_SNAKE_CASE)) if max_length is not None and len(__SCREAMING_SNAKE_CASE) > max_length: A = toks[:max_length] if min_length is not None and len(__SCREAMING_SNAKE_CASE) < min_length and len(__SCREAMING_SNAKE_CASE) > 0: while len(__SCREAMING_SNAKE_CASE) < min_length: A = toks + toks # toks_str = [t[1] for t in toks] A = [t[0] for t in toks] # Ensure consistency A = tokenizer.decode(__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE) if " " not in output_txt and len(__SCREAMING_SNAKE_CASE) > 1: A = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE) + " " + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE) ) if with_prefix_space: A = " " + output_txt A = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE) return output_txt, output_ids def SCREAMING_SNAKE_CASE__ (self : List[Any] , **__SCREAMING_SNAKE_CASE : Any): kwargs.update(self.special_tokens_map) return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Optional[Any]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") # check adding a single token tokenizer.add_tokens("xxx") A = tokenizer("m xxx ɪ" , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , [1_3, 3_9_2, 1_7]) # xxx should be last token tokenizer.add_tokens(["aaa", "bbb", "ccc"]) A = tokenizer("m aaa ɪ ccc" , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , [1_3, 3_9_3, 1_7, 3_9_5]) # aaa and ccc should be after xxx and 2 after aaa A = tokenizer("maɪ c" , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , [3, 2_0_0]) # mai should be <unk> (=3) def SCREAMING_SNAKE_CASE__ (self : Tuple): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(__SCREAMING_SNAKE_CASE , "h ə l oʊ h aʊ ɑːɹ j uː") def SCREAMING_SNAKE_CASE__ (self : List[str]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , tokenizer(__SCREAMING_SNAKE_CASE , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids) def SCREAMING_SNAKE_CASE__ (self : Any): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") A = tokenizer.decode(tokenizer(__SCREAMING_SNAKE_CASE).input_ids) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : str): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8], [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7], ] A = tokenizer.decode(sample_ids[0]) A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , batch_tokens[0]) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]) def SCREAMING_SNAKE_CASE__ (self : List[str]): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(__SCREAMING_SNAKE_CASE , "h ə l oʊ | h aʊ | ɑːɹ | j uː |") def SCREAMING_SNAKE_CASE__ (self : str): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , tokenizer(__SCREAMING_SNAKE_CASE , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids) def SCREAMING_SNAKE_CASE__ (self : Optional[int]): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") # fmt: off A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 1_5, 8, tokenizer.word_delimiter_token_id, 9_8], [tokenizer.word_delimiter_token_id, 2_4, 2_2, tokenizer.word_delimiter_token_id, 5, 2_4, 2_2, 5, 7_7], ] # fmt: on # decode with word_del_token filter A = tokenizer.decode(sample_ids[0]) A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , batch_tokens[0]) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]) # decode with no word_del_token filter A = tokenizer.decode(sample_ids[0] , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , batch_tokens[0]) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ | ɾ l | ɭʲ", "| j ð | s j ð s oːɹ"]) def SCREAMING_SNAKE_CASE__ (self : Dict): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") A = tokenizer.decode(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : List[Any]): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") A = tokenizer.decode(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) self.assertEqual(" ".join([p.strip() for p in phonemes.split(" |")]).strip() , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Dict): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token=__SCREAMING_SNAKE_CASE) A = "Hello how are you" A = tokenizer(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us").input_ids A = tokenizer(__SCREAMING_SNAKE_CASE , phonemizer_lang="fr-fr").input_ids self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) A = tokenizer.decode(__SCREAMING_SNAKE_CASE) A = tokenizer.decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , "h ə l oʊ h aʊ ɑːɹ j uː") self.assertEqual(__SCREAMING_SNAKE_CASE , "ɛ l o h aʊ a ʁ j u") def SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how Are you" A = "hello how are you" A = tokenizer(__SCREAMING_SNAKE_CASE).input_ids A = tokenizer(__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") tokenizer.add_tokens(["!", "?"]) tokenizer.add_special_tokens({"cls_token": "$$$"}) # fmt: off A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8, 3_9_2, 3_9_2, 3_9_3, 3_9_2, 3_9_2, 3_9_3, 3_9_4, 3_9_4], [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7, tokenizer.pad_token_id, 3_9_4, 3_9_4], ] # fmt: on A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ ɾ l ɭʲ!?!? $$$", "j ð s j ð s oːɹ $$$"]) @staticmethod def SCREAMING_SNAKE_CASE__ (__SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]): A = [d[key] for d in offsets] return retrieved_list def SCREAMING_SNAKE_CASE__ (self : Optional[Any]): A = self.get_tokenizer(word_delimiter_token="|") tokenizer.add_tokens("|") # fmt: off # ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ" A = [1_1, 5, 5, 5, 1_5, 1_5, tokenizer.pad_token_id, 1_5, 1_5, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 1_5, 8, 8, 8, tokenizer.word_delimiter_token_id, 9_8] # fmt: on A = tokenizer.decode(__SCREAMING_SNAKE_CASE , output_char_offsets=__SCREAMING_SNAKE_CASE , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) # check Wav2Vec2CTCTokenizerOutput keys for char self.assertEqual(len(outputs.keys()) , 2) self.assertTrue("text" in outputs) self.assertTrue("char_offsets" in outputs) self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) # check that order of chars is correct and identical for both outputs self.assertEqual(" ".join(self.get_from_offsets(outputs["char_offsets"] , "char")) , outputs.text) self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "char") , ["k", "s", "ɾ", "ɾ", "|", "ɾ", "l", "|", "ɭʲ"]) # check that offsets are actually correct for char # 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token, # 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98 self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "start_offset") , [0, 1, 4, 7, 9, 1_1, 1_2, 1_5, 1_6]) self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "end_offset") , [1, 4, 6, 9, 1_0, 1_2, 1_5, 1_6, 1_7]) def SCREAMING_SNAKE_CASE__ (self : Any): A = self.get_tokenizer(word_delimiter_token="|") def check_list_tuples_equal(__SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any]): self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) self.assertTrue(isinstance(outputs_list[0] , __SCREAMING_SNAKE_CASE)) # transform list to ModelOutput A = WavaVecaPhonemeCTCTokenizerOutput( {k: [d[k] for d in outputs_list] for k in outputs_list[0]}) self.assertListEqual(outputs_batch["text"] , outputs_batch_a["text"]) def recursive_check(__SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any]): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): [recursive_check(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) for la, la in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) if "char_offsets" in outputs_batch: recursive_check(outputs_batch["char_offsets"] , outputs_batch_a["char_offsets"]) # fmt: off A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 4, 8, 9_8, 3_2, 3_2, 3_2, 3_2, 4, 3_3, tokenizer.word_delimiter_token_id, 3_2, 3_2, 3_3, 3_4, 3_4], [2_4, 2_2, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 2_4, 2_2, 2_2, 2_2, 4, 5, 7_7, tokenizer.pad_token_id, 2_2, 2_2, 4, 3_4, 3_4, 3_4, 3_4], ] # fmt: on # We assume that `decode` works as expected. All we will check now is # the output type is correct and the output is identical to `decode` # char A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , output_char_offsets=__SCREAMING_SNAKE_CASE) A = [tokenizer.decode(__SCREAMING_SNAKE_CASE , output_char_offsets=__SCREAMING_SNAKE_CASE) for ids in sample_ids] check_list_tuples_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) @unittest.skip("Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes") def SCREAMING_SNAKE_CASE__ (self : Optional[int]): pass @unittest.skip("Wav2Vec2PhonemeTokenizer always puts spaces between phonemes") def SCREAMING_SNAKE_CASE__ (self : Dict): pass @unittest.skip("encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency") def SCREAMING_SNAKE_CASE__ (self : str): pass @unittest.skip("Wav2Vec2PhonemeModel has no max model length => no testing") def SCREAMING_SNAKE_CASE__ (self : Optional[int]): pass def SCREAMING_SNAKE_CASE__ (self : List[str]): A = self.get_tokenizers(do_lower_case=__SCREAMING_SNAKE_CASE) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): A = tokenizer.vocab_size A = len(__SCREAMING_SNAKE_CASE) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A = ["aaaaa bbbbbb", "cccccccccdddddddd"] A = tokenizer.add_tokens(__SCREAMING_SNAKE_CASE) A = tokenizer.vocab_size A = len(__SCREAMING_SNAKE_CASE) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE)) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size + len(__SCREAMING_SNAKE_CASE)) A = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=__SCREAMING_SNAKE_CASE) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE) , 4) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) A = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} A = tokenizer.add_special_tokens(__SCREAMING_SNAKE_CASE) A = tokenizer.vocab_size A = len(__SCREAMING_SNAKE_CASE) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE)) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size_a + len(__SCREAMING_SNAKE_CASE)) A = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=__SCREAMING_SNAKE_CASE) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE) , 6) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[0] , tokens[1]) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokens[-4]) self.assertEqual(tokens[0] , tokenizer.eos_token_id) self.assertEqual(tokens[-3] , tokenizer.pad_token_id) @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") def SCREAMING_SNAKE_CASE__ (self : List[str]): pass @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") def SCREAMING_SNAKE_CASE__ (self : List[Any]): pass def SCREAMING_SNAKE_CASE__ (self : Optional[int]): # The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which # is not the case for Wav2Vec2PhonemeCTCTokenizer. A = self.get_tokenizers(fast=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): A = ["ð", "ɪ", "s", "ɪ", "z", "ɐ", "t", "ɛ", "k", "s", "t"] A = tokenizer.convert_tokens_to_string(__SCREAMING_SNAKE_CASE) self.assertIsInstance(output["text"] , __SCREAMING_SNAKE_CASE)
57
"""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 __A : Tuple = { '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_28, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 50, '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': 10, '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': 10, '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 __UpperCamelCase ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ (cls : int): A = TOKEN HfFolder.save_token(__SCREAMING_SNAKE_CASE) @classmethod def SCREAMING_SNAKE_CASE__ (cls : Dict): 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 SCREAMING_SNAKE_CASE__ (self : Dict): A = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7) 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(__SCREAMING_SNAKE_CASE , getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) # 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(__SCREAMING_SNAKE_CASE , repo_id="test-config" , push_to_hub=__SCREAMING_SNAKE_CASE , 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(__SCREAMING_SNAKE_CASE , getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) def SCREAMING_SNAKE_CASE__ (self : int): A = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7) 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(__SCREAMING_SNAKE_CASE , getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) # 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( __SCREAMING_SNAKE_CASE , repo_id="valid_org/test-config-org" , push_to_hub=__SCREAMING_SNAKE_CASE , 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(__SCREAMING_SNAKE_CASE , getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) def SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): CustomConfig.register_for_auto_class() A = CustomConfig(attribute=4_2) 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=__SCREAMING_SNAKE_CASE) # 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 , 4_2) class __UpperCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ (self : Optional[Any]): 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(__SCREAMING_SNAKE_CASE , c.n_embd , "mismatch for key: n_embd") self.assertEqual(__SCREAMING_SNAKE_CASE , c.resid_pdrop , "mismatch for key: resid_pdrop") self.assertEqual(__SCREAMING_SNAKE_CASE , c.scale_attn_weights , "mismatch for key: scale_attn_weights") self.assertEqual(__SCREAMING_SNAKE_CASE , c.summary_type , "mismatch for key: summary_type") def SCREAMING_SNAKE_CASE__ (self : Dict): 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( __SCREAMING_SNAKE_CASE , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"]) A = [key for key, value in config_common_kwargs.items() if value == getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)] if len(__SCREAMING_SNAKE_CASE) > 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(__SCREAMING_SNAKE_CASE)}.""") def SCREAMING_SNAKE_CASE__ (self : Dict): with self.assertRaises(__SCREAMING_SNAKE_CASE): # 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(__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : int): # A mock response for an HTTP head request to emulate server down A = mock.Mock() A = 5_0_0 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=__SCREAMING_SNAKE_CASE) 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 SCREAMING_SNAKE_CASE__ (self : Optional[int]): # 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 SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): A = AutoConfig.from_pretrained("bert-base-cased") A = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(__SCREAMING_SNAKE_CASE) A = 2 json.dump(configuration.to_dict() , open(os.path.join(__SCREAMING_SNAKE_CASE , "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(__SCREAMING_SNAKE_CASE) 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 = 7_6_8 configuration.save_pretrained(__SCREAMING_SNAKE_CASE) shutil.move(os.path.join(__SCREAMING_SNAKE_CASE , "config.4.0.0.json") , os.path.join(__SCREAMING_SNAKE_CASE , "config.42.0.0.json")) A = AutoConfig.from_pretrained(__SCREAMING_SNAKE_CASE) self.assertEqual(new_configuration.hidden_size , 7_6_8) def SCREAMING_SNAKE_CASE__ (self : Optional[int]): # 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( __SCREAMING_SNAKE_CASE , return_unused_kwargs=__SCREAMING_SNAKE_CASE) self.assertEqual(new_configuration.hidden_size , 2) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(__SCREAMING_SNAKE_CASE , {}) # 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(__SCREAMING_SNAKE_CASE) self.assertEqual(old_configuration.hidden_size , 7_6_8)
57
1
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( '''compression_format, is_archive''' , [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ] , ) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ): '''simple docstring''' __UpperCamelCase :Dict = { """7z""": (seven_zip_file, SevenZipExtractor), """bz2""": (bza_file, BzipaExtractor), """gzip""": (gz_file, GzipExtractor), """lz4""": (lza_file, LzaExtractor), """tar""": (tar_file, TarExtractor), """xz""": (xz_file, XzExtractor), """zip""": (zip_file, ZipExtractor), """zstd""": (zstd_file, ZstdExtractor), } __UpperCamelCase :Optional[Any] = input_paths_and_base_extractors[compression_format] if input_path is None: __UpperCamelCase :Dict = f"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(SCREAMING_SNAKE_CASE__ ) assert base_extractor.is_extractable(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase :Any = tmp_path / ("""extracted""" if is_archive else """extracted.txt""") base_extractor.extract(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name __UpperCamelCase :str = file_path.read_text(encoding='''utf-8''' ) else: __UpperCamelCase :Optional[Any] = output_path.read_text(encoding='''utf-8''' ) __UpperCamelCase :Tuple = text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( '''compression_format, is_archive''' , [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ] , ) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ): '''simple docstring''' __UpperCamelCase :str = { """7z""": seven_zip_file, """bz2""": bza_file, """gzip""": gz_file, """lz4""": lza_file, """tar""": tar_file, """xz""": xz_file, """zip""": zip_file, """zstd""": zstd_file, } __UpperCamelCase :Optional[Any] = input_paths[compression_format] if input_path is None: __UpperCamelCase :int = f"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase :Union[str, Any] = Extractor.infer_extractor_format(SCREAMING_SNAKE_CASE__ ) assert extractor_format is not None __UpperCamelCase :Any = tmp_path / ("""extracted""" if is_archive else """extracted.txt""") Extractor.extract(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name __UpperCamelCase :Dict = file_path.read_text(encoding='''utf-8''' ) else: __UpperCamelCase :int = output_path.read_text(encoding='''utf-8''' ) __UpperCamelCase :Optional[Any] = text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.fixture def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' import tarfile __UpperCamelCase :Tuple = tmp_path / """data_dot_dot""" directory.mkdir() __UpperCamelCase :str = directory / """tar_file_with_dot_dot.tar""" with tarfile.TarFile(SCREAMING_SNAKE_CASE__ , '''w''' ) as f: f.add(SCREAMING_SNAKE_CASE__ , arcname=os.path.join('''..''' , text_file.name ) ) return path @pytest.fixture def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' import tarfile __UpperCamelCase :Tuple = tmp_path / """data_sym_link""" directory.mkdir() __UpperCamelCase :int = directory / """tar_file_with_sym_link.tar""" os.symlink('''..''' , directory / '''subdir''' , target_is_directory=SCREAMING_SNAKE_CASE__ ) with tarfile.TarFile(SCREAMING_SNAKE_CASE__ , '''w''' ) as f: f.add(str(directory / '''subdir''' ) , arcname='''subdir''' ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( '''insecure_tar_file, error_log''' , [('''tar_file_with_dot_dot''', '''illegal path'''), ('''tar_file_with_sym_link''', '''Symlink''')] , ) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :List[Any] = { """tar_file_with_dot_dot""": tar_file_with_dot_dot, """tar_file_with_sym_link""": tar_file_with_sym_link, } __UpperCamelCase :Optional[int] = insecure_tar_files[insecure_tar_file] __UpperCamelCase :List[str] = tmp_path / """extracted""" TarExtractor.extract(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Any = tmpdir / """not_a_zip_file""" # From: https://github.com/python/cpython/pull/5053 __UpperCamelCase :str = ( B"""\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00""" B"""\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I""" B"""DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07""" B"""\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82""" ) with not_a_zip_file.open('''wb''' ) as f: f.write(SCREAMING_SNAKE_CASE__ ) assert zipfile.is_zipfile(str(SCREAMING_SNAKE_CASE__ ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(SCREAMING_SNAKE_CASE__ ) # but we're right
43
# 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 torch from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor from ..utils import is_datasets_available from .base import PipelineTool if is_datasets_available(): from datasets import load_dataset class __snake_case ( lowerCAmelCase ): _a : Union[str, Any]= "microsoft/speecht5_tts" _a : Tuple= ( "This is a tool that reads an English text out loud. It takes an input named `text` which should contain the " "text to read (in English) and returns a waveform object containing the sound." ) _a : Dict= "text_reader" _a : Optional[Any]= SpeechTaProcessor _a : Tuple= SpeechTaForTextToSpeech _a : Optional[int]= SpeechTaHifiGan _a : Union[str, Any]= ["text"] _a : Optional[int]= ["audio"] def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' if self.post_processor is None: lowercase : Any = """microsoft/speecht5_hifigan""" super().setup() def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=None ): '''simple docstring''' lowercase : int = self.pre_processor(text=snake_case ,return_tensors="""pt""" ,truncation=snake_case ) if speaker_embeddings is None: if not is_datasets_available(): raise ImportError("""Datasets needs to be installed if not passing speaker embeddings.""" ) lowercase : Tuple = load_dataset("""Matthijs/cmu-arctic-xvectors""" ,split="""validation""" ) lowercase : List[str] = torch.tensor(embeddings_dataset[7305]["""xvector"""] ).unsqueeze(0 ) return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings} def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' with torch.no_grad(): return self.model.generate_speech(**snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' with torch.no_grad(): return self.post_processor(snake_case ).cpu().detach()
20
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case : Dict = logging.get_logger(__name__) __snake_case : Optional[Any] = { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json""" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCamelCase ( lowerCAmelCase_ ): '''simple docstring''' __snake_case = """roformer""" def __init__( self : Any , lowerCAmelCase_ : Union[str, Any]=5_00_00 , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Union[str, Any]=7_68 , lowerCAmelCase_ : Optional[Any]=12 , lowerCAmelCase_ : Dict=12 , lowerCAmelCase_ : Dict=30_72 , lowerCAmelCase_ : List[str]="gelu" , lowerCAmelCase_ : Optional[int]=0.1 , lowerCAmelCase_ : Optional[int]=0.1 , lowerCAmelCase_ : Any=15_36 , lowerCAmelCase_ : List[Any]=2 , lowerCAmelCase_ : str=0.02 , lowerCAmelCase_ : str=1e-12 , lowerCAmelCase_ : int=0 , lowerCAmelCase_ : Tuple=False , lowerCAmelCase_ : List[str]=True , **lowerCAmelCase_ : List[Any] , ) -> str: '''simple docstring''' super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) A__ : Dict =vocab_size A__ : Tuple =hidden_size if embedding_size is None else embedding_size A__ : int =hidden_size A__ : Optional[int] =num_hidden_layers A__ : str =num_attention_heads A__ : Tuple =hidden_act A__ : Optional[Any] =intermediate_size A__ : Dict =hidden_dropout_prob A__ : str =attention_probs_dropout_prob A__ : int =max_position_embeddings A__ : str =type_vocab_size A__ : List[Any] =initializer_range A__ : Tuple =layer_norm_eps A__ : Union[str, Any] =rotary_value A__ : Dict =use_cache class lowerCamelCase ( lowerCAmelCase_ ): '''simple docstring''' @property def lowercase__ ( self : int ) -> Optional[int]: '''simple docstring''' if self.task == "multiple-choice": A__ : str ={0: """batch""", 1: """choice""", 2: """sequence"""} else: A__ : str ={0: """batch""", 1: """sequence"""} A__ : Union[str, Any] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
352
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( 'The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion' ) __snake_case : Optional[Any] = None __snake_case : Optional[Any] = { '7B': 1_1008, '13B': 1_3824, '30B': 1_7920, '65B': 2_2016, '70B': 2_8672, } __snake_case : Union[str, Any] = { '7B': 1, '7Bf': 1, '13B': 2, '13Bf': 2, '30B': 4, '65B': 8, '70B': 8, '70Bf': 8, } def __lowerCamelCase ( __snake_case : Optional[Any], __snake_case : str=1, __snake_case : Tuple=256 ) -> str: """simple docstring""" return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def __lowerCamelCase ( __snake_case : Tuple ) -> Tuple: """simple docstring""" with open(__snake_case, """r""" ) as f: return json.load(__snake_case ) def __lowerCamelCase ( __snake_case : Optional[int], __snake_case : Tuple ) -> Dict: """simple docstring""" with open(__snake_case, """w""" ) as f: json.dump(__snake_case, __snake_case ) def __lowerCamelCase ( __snake_case : List[Any], __snake_case : Any, __snake_case : Any, __snake_case : Tuple=True ) -> Any: """simple docstring""" os.makedirs(__snake_case, exist_ok=__snake_case ) A__ : List[Any] =os.path.join(__snake_case, """tmp""" ) os.makedirs(__snake_case, exist_ok=__snake_case ) A__ : Dict =read_json(os.path.join(__snake_case, """params.json""" ) ) A__ : Dict =NUM_SHARDS[model_size] A__ : List[str] =params["""n_layers"""] A__ : int =params["""n_heads"""] A__ : str =n_heads // num_shards A__ : Tuple =params["""dim"""] A__ : Union[str, Any] =dim // n_heads A__ : str =1_00_00.0 A__ : Any =1.0 / (base ** (torch.arange(0, __snake_case, 2 ).float() / dims_per_head)) if "n_kv_heads" in params: A__ : Optional[Any] =params["""n_kv_heads"""] # for GQA / MQA A__ : int =n_heads_per_shard // num_key_value_heads A__ : int =dim // num_key_value_heads else: # compatibility with other checkpoints A__ : List[Any] =n_heads A__ : List[str] =n_heads_per_shard A__ : Dict =dim # permute for sliced rotary def permute(__snake_case : Tuple, __snake_case : Optional[int]=n_heads, __snake_case : int=dim, __snake_case : Optional[Any]=dim ): return w.view(__snake_case, dima // n_heads // 2, 2, __snake_case ).transpose(1, 2 ).reshape(__snake_case, __snake_case ) print(f"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) A__ : List[str] =torch.load(os.path.join(__snake_case, """consolidated.00.pth""" ), map_location="""cpu""" ) else: # Sharded A__ : Optional[Any] =[ torch.load(os.path.join(__snake_case, f"consolidated.{i:02d}.pth" ), map_location="""cpu""" ) for i in range(__snake_case ) ] A__ : Optional[Any] =0 A__ : str ={"""weight_map""": {}} for layer_i in range(__snake_case ): A__ : Dict =f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded A__ : Dict ={ f"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[f"layers.{layer_i}.attention.wq.weight"] ), f"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[f"layers.{layer_i}.attention.wk.weight"] ), f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"], f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"], f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"], f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"], f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"], f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"], f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. A__ : Any ={ f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ f"layers.{layer_i}.attention_norm.weight" ].clone(), f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ f"layers.{layer_i}.ffn_norm.weight" ].clone(), } A__ : Optional[Any] =permute( torch.cat( [ loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(__snake_case, __snake_case, __snake_case ) for i in range(__snake_case ) ], dim=0, ).reshape(__snake_case, __snake_case ) ) A__ : int =permute( torch.cat( [ loaded[i][f"layers.{layer_i}.attention.wk.weight"].view( __snake_case, __snake_case, __snake_case ) for i in range(__snake_case ) ], dim=0, ).reshape(__snake_case, __snake_case ), __snake_case, __snake_case, __snake_case, ) A__ : int =torch.cat( [ loaded[i][f"layers.{layer_i}.attention.wv.weight"].view( __snake_case, __snake_case, __snake_case ) for i in range(__snake_case ) ], dim=0, ).reshape(__snake_case, __snake_case ) A__ : List[str] =torch.cat( [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(__snake_case )], dim=1 ) A__ : Optional[int] =torch.cat( [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(__snake_case )], dim=0 ) A__ : str =torch.cat( [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(__snake_case )], dim=1 ) A__ : List[str] =torch.cat( [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(__snake_case )], dim=0 ) A__ : List[Any] =inv_freq for k, v in state_dict.items(): A__ : Optional[Any] =filename param_count += v.numel() torch.save(__snake_case, os.path.join(__snake_case, __snake_case ) ) A__ : Tuple =f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded A__ : Tuple ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: A__ : Any ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(__snake_case )], dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(__snake_case )], dim=0 ), } for k, v in state_dict.items(): A__ : int =filename param_count += v.numel() torch.save(__snake_case, os.path.join(__snake_case, __snake_case ) ) # Write configs A__ : Union[str, Any] ={"""total_size""": param_count * 2} write_json(__snake_case, os.path.join(__snake_case, """pytorch_model.bin.index.json""" ) ) A__ : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 A__ : List[Any] =params["""multiple_of"""] if """multiple_of""" in params else 256 A__ : int =LlamaConfig( hidden_size=__snake_case, intermediate_size=compute_intermediate_size(__snake_case, __snake_case, __snake_case ), num_attention_heads=params["""n_heads"""], num_hidden_layers=params["""n_layers"""], rms_norm_eps=params["""norm_eps"""], num_key_value_heads=__snake_case, ) config.save_pretrained(__snake_case ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) A__ : List[Any] =LlamaForCausalLM.from_pretrained(__snake_case, torch_dtype=torch.floataa, low_cpu_mem_usage=__snake_case ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(__snake_case, safe_serialization=__snake_case ) shutil.rmtree(__snake_case ) def __lowerCamelCase ( __snake_case : Union[str, Any], __snake_case : Dict ) -> Tuple: """simple docstring""" A__ : List[Any] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) A__ : List[str] =tokenizer_class(__snake_case ) tokenizer.save_pretrained(__snake_case ) def __lowerCamelCase ( ) -> Any: """simple docstring""" A__ : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""", help="""Location of LLaMA weights, which contains tokenizer.model and model folders""", ) parser.add_argument( """--model_size""", choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""], ) parser.add_argument( """--output_dir""", help="""Location to write HF model and tokenizer""", ) parser.add_argument("""--safe_serialization""", type=__snake_case, help="""Whether or not to save using `safetensors`.""" ) A__ : Any =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir, input_base_path=os.path.join(args.input_dir, args.model_size ), model_size=args.model_size, safe_serialization=args.safe_serialization, ) A__ : List[Any] =os.path.join(args.input_dir, """tokenizer.model""" ) write_tokenizer(args.output_dir, __snake_case ) if __name__ == "__main__": main()
136
0
"""simple docstring""" import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def _A ( UpperCamelCase_ : List[Any], UpperCamelCase_ : Tuple=False) -> int: '''simple docstring''' try: __lowercase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __lowercase = default else: # KEY is set, convert it to True or False. try: __lowercase = strtobool(UpperCamelCase_) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"""If set, {key} must be yes or no.""") return _value _a = parse_flag_from_env('RUN_SLOW', default=False) def _A ( UpperCamelCase_ : int) -> Optional[int]: '''simple docstring''' return unittest.skip("Test was skipped")(UpperCamelCase_) def _A ( UpperCamelCase_ : Any) -> Optional[int]: '''simple docstring''' return unittest.skipUnless(_run_slow_tests, "test is slow")(UpperCamelCase_) def _A ( UpperCamelCase_ : Tuple) -> List[Any]: '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available(), "test requires only a CPU")(UpperCamelCase_) def _A ( UpperCamelCase_ : int) -> Any: '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available(), "test requires a GPU")(UpperCamelCase_) def _A ( UpperCamelCase_ : Optional[int]) -> Tuple: '''simple docstring''' return unittest.skipUnless(is_xpu_available(), "test requires a XPU")(UpperCamelCase_) def _A ( UpperCamelCase_ : Optional[int]) -> Dict: '''simple docstring''' return unittest.skipUnless(is_mps_available(), "test requires a `mps` backend support in `torch`")(UpperCamelCase_) def _A ( UpperCamelCase_ : int) -> List[Any]: '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available(), "test requires the Hugging Face suite")(UpperCamelCase_) def _A ( UpperCamelCase_ : Union[str, Any]) -> Tuple: '''simple docstring''' return unittest.skipUnless(is_bnb_available(), "test requires the bitsandbytes library")(UpperCamelCase_) def _A ( UpperCamelCase_ : Optional[Any]) -> int: '''simple docstring''' return unittest.skipUnless(is_tpu_available(), "test requires TPU")(UpperCamelCase_) def _A ( UpperCamelCase_ : str) -> List[Any]: '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1, "test requires a GPU")(UpperCamelCase_) def _A ( UpperCamelCase_ : Union[str, Any]) -> List[str]: '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1, "test requires a XPU")(UpperCamelCase_) def _A ( UpperCamelCase_ : List[Any]) -> str: '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1, "test requires multiple GPUs")(UpperCamelCase_) def _A ( UpperCamelCase_ : Optional[int]) -> str: '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1, "test requires multiple XPUs")(UpperCamelCase_) def _A ( UpperCamelCase_ : str) -> int: '''simple docstring''' return unittest.skipUnless(is_safetensors_available(), "test requires safetensors")(UpperCamelCase_) def _A ( UpperCamelCase_ : Dict) -> str: '''simple docstring''' return unittest.skipUnless(is_deepspeed_available(), "test requires DeepSpeed")(UpperCamelCase_) def _A ( UpperCamelCase_ : List[str]) -> Dict: '''simple docstring''' return unittest.skipUnless(is_torch_version(">=", "1.12.0"), "test requires torch version >= 1.12.0")(UpperCamelCase_) def _A ( UpperCamelCase_ : Dict=None, UpperCamelCase_ : int=None) -> int: '''simple docstring''' if test_case is None: return partial(UpperCamelCase_, version=UpperCamelCase_) return unittest.skipUnless(is_torch_version(">=", UpperCamelCase_), F"""test requires torch version >= {version}""")(UpperCamelCase_) def _A ( UpperCamelCase_ : List[Any]) -> Any: '''simple docstring''' return unittest.skipUnless(is_tensorboard_available(), "test requires Tensorboard")(UpperCamelCase_) def _A ( UpperCamelCase_ : Optional[Any]) -> Union[str, Any]: '''simple docstring''' return unittest.skipUnless(is_wandb_available(), "test requires wandb")(UpperCamelCase_) def _A ( UpperCamelCase_ : Optional[int]) -> Tuple: '''simple docstring''' return unittest.skipUnless(is_comet_ml_available(), "test requires comet_ml")(UpperCamelCase_) _a = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def _A ( UpperCamelCase_ : List[str]) -> str: '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available, "test requires at least one tracker to be available and for `comet_ml` to not be installed", )(UpperCamelCase_) class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Tuple = True @classmethod def _lowercase ( cls : Dict ): __lowercase = tempfile.mkdtemp() @classmethod def _lowercase ( cls : List[str] ): if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def _lowercase ( self : Union[str, Any] ): if self.clear_on_setup: for path in Path(self.tmpdir ).glob("**/*" ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(UpperCAmelCase__ ) class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def _lowercase ( self : Optional[Any] ): super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def _lowercase ( self : Optional[int], UpperCAmelCase__ : Union[mock.Mock, List[mock.Mock]] ): __lowercase = mocks if isinstance(UpperCAmelCase__, (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def _A ( UpperCamelCase_ : int) -> int: '''simple docstring''' __lowercase = AcceleratorState() __lowercase = tensor[None].clone().to(state.device) __lowercase = gather(UpperCamelCase_).cpu() __lowercase = tensor[0].cpu() for i in range(tensors.shape[0]): if not torch.equal(tensors[i], UpperCamelCase_): return False return True class _lowerCAmelCase : """simple docstring""" def __init__( self : Union[str, Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[str], UpperCAmelCase__ : Tuple ): __lowercase = returncode __lowercase = stdout __lowercase = stderr async def _A ( UpperCamelCase_ : int, UpperCamelCase_ : List[str]) -> Any: '''simple docstring''' while True: __lowercase = await stream.readline() if line: callback(UpperCamelCase_) else: break async def _A ( UpperCamelCase_ : Optional[int], UpperCamelCase_ : List[str]=None, UpperCamelCase_ : Optional[Any]=None, UpperCamelCase_ : List[str]=None, UpperCamelCase_ : Dict=False, UpperCamelCase_ : int=False) -> _RunOutput: '''simple docstring''' if echo: print("\nRunning: ", " ".join(UpperCamelCase_)) __lowercase = await asyncio.create_subprocess_exec( cmd[0], *cmd[1:], stdin=UpperCamelCase_, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=UpperCamelCase_, ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __lowercase = [] __lowercase = [] def tee(UpperCamelCase_ : Any, UpperCamelCase_ : List[Any], UpperCamelCase_ : Dict, UpperCamelCase_ : int=""): __lowercase = line.decode("utf-8").rstrip() sink.append(UpperCamelCase_) if not quiet: print(UpperCamelCase_, UpperCamelCase_, file=UpperCamelCase_) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout, lambda UpperCamelCase_: tee(UpperCamelCase_, UpperCamelCase_, sys.stdout, label="stdout:"))), asyncio.create_task(_read_stream(p.stderr, lambda UpperCamelCase_: tee(UpperCamelCase_, UpperCamelCase_, sys.stderr, label="stderr:"))), ], timeout=UpperCamelCase_, ) return _RunOutput(await p.wait(), UpperCamelCase_, UpperCamelCase_) def _A ( UpperCamelCase_ : str, UpperCamelCase_ : Optional[Any]=None, UpperCamelCase_ : Dict=None, UpperCamelCase_ : str=180, UpperCamelCase_ : Optional[int]=False, UpperCamelCase_ : int=True) -> _RunOutput: '''simple docstring''' __lowercase = asyncio.get_event_loop() __lowercase = loop.run_until_complete( _stream_subprocess(UpperCamelCase_, env=UpperCamelCase_, stdin=UpperCamelCase_, timeout=UpperCamelCase_, quiet=UpperCamelCase_, echo=UpperCamelCase_)) __lowercase = " ".join(UpperCamelCase_) if result.returncode > 0: __lowercase = "\n".join(result.stderr) raise RuntimeError( F"""'{cmd_str}' failed with returncode {result.returncode}\n\n""" F"""The combined stderr from workers follows:\n{stderr}""") return result class _lowerCAmelCase ( lowercase ): """simple docstring""" pass def _A ( UpperCamelCase_ : List[str], UpperCamelCase_ : Optional[int]=False) -> Union[str, Any]: '''simple docstring''' try: __lowercase = subprocess.check_output(UpperCamelCase_, stderr=subprocess.STDOUT) if return_stdout: if hasattr(UpperCamelCase_, "decode"): __lowercase = output.decode("utf-8") return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F"""Command `{" ".join(UpperCamelCase_)}` failed with the following error:\n\n{e.output.decode()}""") from e
17
def _lowerCAmelCase ( lowerCAmelCase_ :int | float | str )->tuple[int, int]: '''simple docstring''' try: snake_case_ = float(lowerCAmelCase_ ) except ValueError: raise ValueError("Please enter a valid number" ) snake_case_ = decimal - int(lowerCAmelCase_ ) if fractional_part == 0: return int(lowerCAmelCase_ ), 1 else: snake_case_ = len(str(lowerCAmelCase_ ).split("." )[1] ) snake_case_ = int(decimal * (10**number_of_frac_digits) ) snake_case_ = 10**number_of_frac_digits snake_case_ , snake_case_ = denominator, numerator while True: snake_case_ = dividend % divisor if remainder == 0: break snake_case_ , snake_case_ = divisor, remainder snake_case_ , snake_case_ = numerator / divisor, denominator / divisor return int(lowerCAmelCase_ ), int(lowerCAmelCase_ ) if __name__ == "__main__": print(F'''{decimal_to_fraction(2) = }''') print(F'''{decimal_to_fraction(89.0) = }''') print(F'''{decimal_to_fraction('67') = }''') print(F'''{decimal_to_fraction('45.0') = }''') print(F'''{decimal_to_fraction(1.5) = }''') print(F'''{decimal_to_fraction('6.25') = }''') print(F'''{decimal_to_fraction('78td') = }''')
159
0
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[int]: for param in module.parameters(): __lowerCamelCase = False def __lowerCAmelCase ( ) -> Union[str, Any]: __lowerCamelCase = '''cuda''' if torch.cuda.is_available() else '''cpu''' if torch.backends.mps.is_available() and torch.backends.mps.is_built(): __lowerCamelCase = '''mps''' if device == "mps": print( '''WARNING: MPS currently doesn\'t seem to work, and messes up backpropagation without any visible torch''' ''' errors. I recommend using CUDA on a colab notebook or CPU instead if you\'re facing inexplicable issues''' ''' with generations.''' ) return device def __lowerCAmelCase ( UpperCamelCase__ ) -> int: __lowerCamelCase = plt.imshow(UpperCamelCase__ ) fig.axes.get_xaxis().set_visible(UpperCamelCase__ ) fig.axes.get_yaxis().set_visible(UpperCamelCase__ ) plt.show() def __lowerCAmelCase ( ) -> Optional[Any]: __lowerCamelCase = datetime.now() __lowerCamelCase = current_time.strftime('''%H:%M:%S''' ) return timestamp
237
'''simple docstring''' from __future__ import annotations from typing import Any def __lowerCAmelCase ( UpperCamelCase__ ) -> None: create_state_space_tree(UpperCamelCase__ , [] , 0 ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> None: if index == len(UpperCamelCase__ ): print(UpperCamelCase__ ) return create_state_space_tree(UpperCamelCase__ , UpperCamelCase__ , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(UpperCamelCase__ , UpperCamelCase__ , index + 1 ) current_subsequence.pop() if __name__ == "__main__": __UpperCAmelCase =[3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
237
1
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 A__ ( snake_case__ , unittest.TestCase ): """simple docstring""" __magic_name__ = BlenderbotSmallTokenizer __magic_name__ = False def a_ ( self ): super().setUp() snake_case = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] snake_case = dict(zip(__snake_case , range(len(__snake_case ) ) ) ) snake_case = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] snake_case = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__snake_case ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__snake_case ) ) def a_ ( self , **__snake_case ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__snake_case ) def a_ ( self , __snake_case ): snake_case = '''adapt act apte''' snake_case = '''adapt act apte''' return input_text, output_text def a_ ( self ): snake_case = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case = '''adapt act apte''' snake_case = ['''adapt''', '''act''', '''ap@@''', '''te'''] snake_case = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) snake_case = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] snake_case = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , __snake_case ) def a_ ( self ): snake_case = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [1_3_8_4] snake_case = '''I am a small frog.''' snake_case = tok([src_text] , padding=__snake_case , truncation=__snake_case )['''input_ids'''] snake_case = tok.batch_decode(__snake_case , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def a_ ( self ): snake_case = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) snake_case = '''I am a small frog .''' snake_case = '''.''' snake_case = tok(__snake_case )['''input_ids'''] snake_case = tok(__snake_case )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
127
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) _SCREAMING_SNAKE_CASE : List[str] = "hf-internal-testing/tiny-random-bert" _SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert") _SCREAMING_SNAKE_CASE : Optional[int] = "9b8c223d42b2188cb49d29af482996f9d0f3e5a6" class A__ ( unittest.TestCase ): """simple docstring""" def a_ ( self ): snake_case = cached_file(__snake_case , __snake_case ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__snake_case ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__snake_case , __snake_case ) ) ) with open(os.path.join(__snake_case , '''refs''' , '''main''' ) ) as f: snake_case = f.read() self.assertEqual(__snake_case , os.path.join(__snake_case , '''snapshots''' , __snake_case , __snake_case ) ) self.assertTrue(os.path.isfile(__snake_case ) ) # File is cached at the same place the second time. snake_case = cached_file(__snake_case , __snake_case ) self.assertEqual(__snake_case , __snake_case ) # Using a specific revision to test the full commit hash. snake_case = cached_file(__snake_case , __snake_case , revision='''9b8c223''' ) self.assertEqual(__snake_case , os.path.join(__snake_case , '''snapshots''' , __snake_case , __snake_case ) ) def a_ ( self ): with self.assertRaisesRegex(__snake_case , '''is not a valid model identifier''' ): snake_case = cached_file('''tiny-random-bert''' , __snake_case ) with self.assertRaisesRegex(__snake_case , '''is not a valid git identifier''' ): snake_case = cached_file(__snake_case , __snake_case , revision='''aaaa''' ) with self.assertRaisesRegex(__snake_case , '''does not appear to have a file named''' ): snake_case = cached_file(__snake_case , '''conf''' ) def a_ ( self ): with self.assertRaisesRegex(__snake_case , '''does not appear to have a file named''' ): snake_case = cached_file(__snake_case , '''conf''' ) with open(os.path.join(__snake_case , '''refs''' , '''main''' ) ) as f: snake_case = f.read() self.assertTrue(os.path.isfile(os.path.join(__snake_case , '''.no_exist''' , __snake_case , '''conf''' ) ) ) snake_case = cached_file(__snake_case , '''conf''' , _raise_exceptions_for_missing_entries=__snake_case ) self.assertIsNone(__snake_case ) snake_case = cached_file(__snake_case , '''conf''' , local_files_only=__snake_case , _raise_exceptions_for_missing_entries=__snake_case ) self.assertIsNone(__snake_case ) snake_case = mock.Mock() snake_case = 5_0_0 snake_case = {} snake_case = HTTPError snake_case = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__snake_case ) as mock_head: snake_case = cached_file(__snake_case , '''conf''' , _raise_exceptions_for_connection_errors=__snake_case ) self.assertIsNone(__snake_case ) # This check we did call the fake head request mock_head.assert_called() def a_ ( self ): self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __snake_case ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __snake_case ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __snake_case ) ) def a_ ( self ): # `get_file_from_repo` returns None if the file does not exist self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__snake_case , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __snake_case ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__snake_case , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __snake_case , revision='''ahaha''' ) snake_case = get_file_from_repo('''bert-base-cased''' , __snake_case ) # The name is the cached name which is not very easy to test, so instead we load the content. snake_case = json.loads(open(__snake_case , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def a_ ( self ): with tempfile.TemporaryDirectory() as tmp_dir: snake_case = Path(__snake_case ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__snake_case , '''a.txt''' ) , str(__snake_case ) ) self.assertIsNone(get_file_from_repo(__snake_case , '''b.txt''' ) )
127
1
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class A ( unittest.TestCase ): def __init__( self, UpperCamelCase__, UpperCamelCase__=100, UpperCamelCase__=13, UpperCamelCase__=30, UpperCamelCase__=2, UpperCamelCase__=3, UpperCamelCase__=True, UpperCamelCase__=True, UpperCamelCase__=32, UpperCamelCase__=5, UpperCamelCase__=4, UpperCamelCase__=37, UpperCamelCase__="gelu", UpperCamelCase__=0.1, UpperCamelCase__=0.1, UpperCamelCase__=10, UpperCamelCase__=0.02, UpperCamelCase__=3, ): """simple docstring""" lowerCAmelCase_ = parent lowerCAmelCase_ = vocab_size lowerCAmelCase_ = batch_size lowerCAmelCase_ = image_size lowerCAmelCase_ = patch_size lowerCAmelCase_ = num_channels lowerCAmelCase_ = is_training lowerCAmelCase_ = use_labels lowerCAmelCase_ = hidden_size lowerCAmelCase_ = num_hidden_layers lowerCAmelCase_ = num_attention_heads lowerCAmelCase_ = intermediate_size lowerCAmelCase_ = hidden_act lowerCAmelCase_ = hidden_dropout_prob lowerCAmelCase_ = attention_probs_dropout_prob lowerCAmelCase_ = type_sequence_label_size lowerCAmelCase_ = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase_ = (image_size // patch_size) ** 2 lowerCAmelCase_ = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase_ = None if self.use_labels: lowerCAmelCase_ = ids_tensor([self.batch_size], self.type_sequence_label_size ) lowerCAmelCase_ = BeitConfig( vocab_size=self.vocab_size, image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=UpperCamelCase__, initializer_range=self.initializer_range, ) return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" lowerCAmelCase_ = FlaxBeitModel(config=UpperCamelCase__ ) lowerCAmelCase_ = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" lowerCAmelCase_ = FlaxBeitForMaskedImageModeling(config=UpperCamelCase__ ) lowerCAmelCase_ = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length - 1, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" lowerCAmelCase_ = self.type_sequence_label_size lowerCAmelCase_ = FlaxBeitForImageClassification(config=UpperCamelCase__ ) lowerCAmelCase_ = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCAmelCase_ = 1 lowerCAmelCase_ = FlaxBeitForImageClassification(UpperCamelCase__ ) lowerCAmelCase_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase_ = model(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.prepare_config_and_inputs() ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) = config_and_inputs lowerCAmelCase_ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class A ( __UpperCAmelCase , unittest.TestCase ): __snake_case = ( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = FlaxBeitModelTester(self ) lowerCAmelCase_ = ConfigTester(self, config_class=UpperCamelCase__, has_text_modality=UpperCamelCase__, hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ , lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_ = model_class(UpperCamelCase__ ) lowerCAmelCase_ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase_ = [*signature.parameters.keys()] lowerCAmelCase_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1], UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ , lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCAmelCase_ = self._prepare_for_class(UpperCamelCase__, UpperCamelCase__ ) lowerCAmelCase_ = model_class(UpperCamelCase__ ) @jax.jit def model_jitted(UpperCamelCase__, **UpperCamelCase__ ): return model(pixel_values=UpperCamelCase__, **UpperCamelCase__ ) with self.subTest('''JIT Enabled''' ): lowerCAmelCase_ = model_jitted(**UpperCamelCase__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowerCAmelCase_ = model_jitted(**UpperCamelCase__ ).to_tuple() self.assertEqual(len(UpperCamelCase__ ), len(UpperCamelCase__ ) ) for jitted_output, output in zip(UpperCamelCase__, UpperCamelCase__ ): self.assertEqual(jitted_output.shape, output.shape ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" for model_class_name in self.all_model_classes: lowerCAmelCase_ = model_class_name.from_pretrained('''microsoft/beit-base-patch16-224''' ) lowerCAmelCase_ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(UpperCamelCase__ ) def __UpperCamelCase ( ): lowerCAmelCase_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @require_flax class A ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = FlaxBeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k''' ) lowerCAmelCase_ = self.default_image_processor lowerCAmelCase_ = prepare_img() lowerCAmelCase_ = image_processor(images=UpperCamelCase__, return_tensors='''np''' ).pixel_values # prepare bool_masked_pos lowerCAmelCase_ = np.ones((1, 196), dtype=UpperCamelCase__ ) # forward pass lowerCAmelCase_ = model(pixel_values=UpperCamelCase__, bool_masked_pos=UpperCamelCase__ ) lowerCAmelCase_ = outputs.logits # verify the logits lowerCAmelCase_ = (1, 196, 8192) self.assertEqual(logits.shape, UpperCamelCase__ ) lowerCAmelCase_ = np.array( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3], UpperCamelCase__, atol=1E-2 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224''' ) lowerCAmelCase_ = self.default_image_processor lowerCAmelCase_ = prepare_img() lowerCAmelCase_ = image_processor(images=UpperCamelCase__, return_tensors='''np''' ) # forward pass lowerCAmelCase_ = model(**UpperCamelCase__ ) lowerCAmelCase_ = outputs.logits # verify the logits lowerCAmelCase_ = (1, 1000) self.assertEqual(logits.shape, UpperCamelCase__ ) lowerCAmelCase_ = np.array([-1.2_385, -1.0_987, -1.0_108] ) self.assertTrue(np.allclose(logits[0, :3], UpperCamelCase__, atol=1E-4 ) ) lowerCAmelCase_ = 281 self.assertEqual(logits.argmax(-1 ).item(), UpperCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k''' ) lowerCAmelCase_ = self.default_image_processor lowerCAmelCase_ = prepare_img() lowerCAmelCase_ = image_processor(images=UpperCamelCase__, return_tensors='''np''' ) # forward pass lowerCAmelCase_ = model(**UpperCamelCase__ ) lowerCAmelCase_ = outputs.logits # verify the logits lowerCAmelCase_ = (1, 2_1841) self.assertEqual(logits.shape, UpperCamelCase__ ) lowerCAmelCase_ = np.array([1.6_881, -0.2_787, 0.5_901] ) self.assertTrue(np.allclose(logits[0, :3], UpperCamelCase__, atol=1E-4 ) ) lowerCAmelCase_ = 2396 self.assertEqual(logits.argmax(-1 ).item(), UpperCamelCase__ )
352
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCAmelCase_ = UNetaDModel( block_out_channels=(32, 64), layers_per_block=2, sample_size=32, in_channels=3, out_channels=3, down_block_types=('''DownBlock2D''', '''AttnDownBlock2D'''), up_block_types=('''AttnUpBlock2D''', '''UpBlock2D'''), ) return model def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = self.dummy_uncond_unet lowerCAmelCase_ = KarrasVeScheduler() lowerCAmelCase_ = KarrasVePipeline(unet=UpperCamelCase__, scheduler=UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = pipe(num_inference_steps=2, generator=UpperCamelCase__, output_type='''numpy''' ).images lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = pipe(num_inference_steps=2, generator=UpperCamelCase__, output_type='''numpy''', return_dict=UpperCamelCase__ )[0] lowerCAmelCase_ = image[0, -3:, -3:, -1] lowerCAmelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase_ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class A ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = '''google/ncsnpp-celebahq-256''' lowerCAmelCase_ = UNetaDModel.from_pretrained(UpperCamelCase__ ) lowerCAmelCase_ = KarrasVeScheduler() lowerCAmelCase_ = KarrasVePipeline(unet=UpperCamelCase__, scheduler=UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = pipe(num_inference_steps=20, generator=UpperCamelCase__, output_type='''numpy''' ).images lowerCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowerCAmelCase_ = np.array([0.578, 0.5_811, 0.5_924, 0.5_809, 0.587, 0.5_886, 0.5_861, 0.5_802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
167
0
from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING _UpperCAmelCase : str = logging.get_logger(__name__) @add_end_docstrings(lowercase_ ) class lowercase ( lowercase_ ): def __init__( self , *snake_case , **snake_case ): super().__init__(*snake_case , **snake_case ) requires_backends(self , 'decord' ) self.check_model_type(snake_case ) def a ( self , snake_case=None , snake_case=None , snake_case=None ): snake_case_ = {} if frame_sampling_rate is not None: snake_case_ = frame_sampling_rate if num_frames is not None: snake_case_ = num_frames snake_case_ = {} if top_k is not None: snake_case_ = top_k return preprocess_params, {}, postprocess_params def __call__( self , snake_case , **snake_case ): return super().__call__(snake_case , **snake_case ) def a ( self , snake_case , snake_case=None , snake_case=1 ): if num_frames is None: snake_case_ = self.model.config.num_frames if video.startswith('http://' ) or video.startswith('https://' ): snake_case_ = BytesIO(requests.get(snake_case ).content ) snake_case_ = VideoReader(snake_case ) videoreader.seek(0 ) snake_case_ = 0 snake_case_ = num_frames * frame_sampling_rate - 1 snake_case_ = np.linspace(snake_case , snake_case , num=snake_case , dtype=np.intaa ) snake_case_ = videoreader.get_batch(snake_case ).asnumpy() snake_case_ = list(snake_case ) snake_case_ = self.image_processor(snake_case , return_tensors=self.framework ) return model_inputs def a ( self , snake_case ): snake_case_ = self.model(**snake_case ) return model_outputs def a ( self , snake_case , snake_case=5 ): if top_k > self.model.config.num_labels: snake_case_ = self.model.config.num_labels if self.framework == "pt": snake_case_ = model_outputs.logits.softmax(-1 )[0] snake_case_ , snake_case_ = probs.topk(snake_case ) else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) snake_case_ = scores.tolist() snake_case_ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case , snake_case )]
285
from PIL import Image def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' snake_case_ = (259 * (level + 255)) / (255 * (259 - level)) def contrast(UpperCamelCase__ ) -> int: return int(128 + factor * (c - 128) ) return img.point(UpperCamelCase__ ) if __name__ == "__main__": # Load image with Image.open("""image_data/lena.jpg""") as img: # Change contrast to 170 _UpperCAmelCase : Tuple = change_contrast(img, 170) cont_img.save("""image_data/lena_high_contrast.png""", format="""png""")
285
1
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowerCamelCase__ ( UpperCamelCase__ : str ) -> Optional[int]: '''simple docstring''' _snake_case = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase__ ( UpperCamelCase__ : Tuple ) -> Union[str, Any]: '''simple docstring''' _snake_case , _snake_case = emb.weight.shape _snake_case = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) _snake_case = emb.weight.data return lin_layer def lowerCamelCase__ ( UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Any=None ) -> List[str]: '''simple docstring''' _snake_case = {} for old_key in state_dict.keys(): _snake_case = old_key if "moe_layer.experts." in key: if expert_idx is not None: _snake_case = key.replace('moe_layer.experts.0' , F'''ffn.experts.expert_{expert_idx}''' ) else: _snake_case = key.replace('moe_layer.experts.' , 'ffn.experts.expert_' ) if "gate" in key: _snake_case = key.replace('.moe_layer.gate.wg' , '.ffn.router.classifier' ) if "fc2" and "experts" not in key: _snake_case = key.replace('.fc2.' , '.ffn.fc2.' ) if "fc1" and "experts" not in key: _snake_case = key.replace('.fc1.' , '.ffn.fc1.' ) if ".encoder_attn." in key: _snake_case = key.replace('.encoder_attn.' , '.cross_attention.' ) if "encoder_attn_layer_norm" in key: _snake_case = key.replace('encoder_attn_layer_norm' , 'cross_attention_layer_norm' ) if "final_layer_norm" in key: _snake_case = key.replace('final_layer_norm' , 'ff_layer_norm' ) _snake_case = state_dict[old_key] return new_dict def lowerCamelCase__ ( UpperCamelCase__ : int , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str = WEIGHTS_NAME ) -> Union[str, Any]: '''simple docstring''' _snake_case = [] _snake_case = 0 os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) for expert in range(UpperCamelCase__ ): _snake_case = switch_checkpoint_path + F'''-rank-{expert}.pt''' if os.path.isfile(UpperCamelCase__ ): _snake_case = torch.load(UpperCamelCase__ )['model'] remove_ignore_keys_(UpperCamelCase__ ) _snake_case = rename_fairseq_keys(UpperCamelCase__ , UpperCamelCase__ ) _snake_case = os.path.join( UpperCamelCase__ , weights_name.replace('.bin' , F'''-{len(UpperCamelCase__ )+1:05d}-of-???.bin''' ) ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(UpperCamelCase__ )[0]].dtype ) # Add the last block _snake_case = os.path.join(UpperCamelCase__ , weights_name.replace('.bin' , F'''-{len(UpperCamelCase__ )+1:05d}-of-???.bin''' ) ) _snake_case = torch.load(switch_checkpoint_path + '-shared.pt' )['model'] remove_ignore_keys_(UpperCamelCase__ ) _snake_case = rename_fairseq_keys(UpperCamelCase__ , UpperCamelCase__ ) _snake_case = shared_weights['decoder.embed_tokens.weight'] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(UpperCamelCase__ ) == 1: _snake_case = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(UpperCamelCase__ , UpperCamelCase__ ) # Otherwise, let's build the index _snake_case = {} for idx, shard in enumerate(UpperCamelCase__ ): _snake_case = weights_name.replace('.bin' , F'''-{idx+1:05d}-of-{len(UpperCamelCase__ ):05d}.bin''' ) _snake_case = os.path.join(UpperCamelCase__ , weights_name.replace('.bin' , F'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(UpperCamelCase__ , os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) for key in shard: _snake_case = shard_file # Add the metadata _snake_case = {'total_size': total_size} _snake_case = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) , 'w' , encoding='utf-8' ) as f: _snake_case = json.dumps(UpperCamelCase__ , indent=2 , sort_keys=UpperCamelCase__ ) + '\n' f.write(UpperCamelCase__ ) return metadata, index if __name__ == "__main__": UpperCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--nllb_moe_checkpoint_path""", default="""/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000""", type=str, required=False, help="""Path to a directory containing a folder per layer. Follows the original Google format.""", ) parser.add_argument("""--dtype""", default="""float32""", type=str, required=False, help="""dtype of the saved model""") parser.add_argument( """--pytorch_dump_folder_path""", default="""/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b""", type=str, required=False, help="""Path to the output pytorch model.""", ) UpperCAmelCase_ = parser.parse_args() UpperCAmelCase_ , UpperCAmelCase_ = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) UpperCAmelCase_ = NllbMoeConfig.from_pretrained( """facebook/nllb-200-3.3B""", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) UpperCAmelCase_ = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print("""Done""") model.save_pretrained(args.pytorch_dump_folder_path)
295
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path UpperCAmelCase_ = [ {"""dataset""": """wikipedia""", """config_name""": """20220301.de"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.en"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.fr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.frr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.it"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.simple"""}, {"""dataset""": """snli""", """config_name""": """plain_text"""}, {"""dataset""": """eli5""", """config_name""": """LFQA_reddit"""}, {"""dataset""": """wiki40b""", """config_name""": """en"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.compressed"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.no_index"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.multiset.no_index"""}, {"""dataset""": """natural_questions""", """config_name""": """default"""}, ] def lowerCamelCase__ ( UpperCamelCase__ : Dict=True ) -> Dict: '''simple docstring''' if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=_lowerCamelCase ) ) class UpperCamelCase_ ( _lowerCamelCase ): lowerCAmelCase_ = None lowerCAmelCase_ = None def lowerCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ) -> Union[str, Any]: with TemporaryDirectory() as tmp_dir: _snake_case = dataset_module_factory(lowerCAmelCase_ , cache_dir=lowerCAmelCase_ ) _snake_case = import_main_class(dataset_module.module_path , dataset=lowerCAmelCase_ ) _snake_case = builder_cls( cache_dir=lowerCAmelCase_ , config_name=lowerCAmelCase_ , hash=dataset_module.hash , ) _snake_case = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=lowerCAmelCase_ ).replace(os.sep , '/' ), config.DATASET_INFO_FILENAME, ] ) _snake_case = cached_path(lowerCAmelCase_ , cache_dir=lowerCAmelCase_ ) self.assertTrue(os.path.exists(lowerCAmelCase_ ) ) @pytest.mark.integration def lowerCamelCase__ ( UpperCamelCase__ : Any ) -> Tuple: '''simple docstring''' _snake_case = tmp_path_factory.mktemp('test_hf_gcp' ) / 'test_wikipedia_simple' _snake_case = dataset_module_factory('wikipedia' , cache_dir=UpperCamelCase__ ) _snake_case = import_main_class(dataset_module.module_path ) _snake_case = builder_cls( cache_dir=UpperCamelCase__ , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam _snake_case = None builder_instance.download_and_prepare() _snake_case = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ ( UpperCamelCase__ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' _snake_case = dataset_module_factory('wikipedia' , cache_dir=UpperCamelCase__ ) _snake_case = import_main_class(dataset_module.module_path , dataset=UpperCamelCase__ ) _snake_case = builder_cls( cache_dir=UpperCamelCase__ , config_name='20220301.frr' , hash=dataset_module.hash , ) _snake_case = builder_instance.as_streaming_dataset() assert ds assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) assert "train" in ds assert isinstance(ds['train'] , UpperCamelCase__ ) assert next(iter(ds['train'] ) )
295
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : str = { """configuration_conditional_detr""": [ """CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConditionalDetrConfig""", """ConditionalDetrOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : str = ["""ConditionalDetrFeatureExtractor"""] a_ : Any = ["""ConditionalDetrImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ """CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConditionalDetrForObjectDetection""", """ConditionalDetrForSegmentation""", """ConditionalDetrModel""", """ConditionalDetrPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys a_ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
55
'''simple docstring''' import math def __snake_case ( UpperCAmelCase_ : int ): lowerCamelCase_ = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(UpperCAmelCase_ ) def __snake_case ( UpperCAmelCase_ : float = 1 / 12345 ): lowerCamelCase_ = 0 lowerCamelCase_ = 0 lowerCamelCase_ = 3 while True: lowerCamelCase_ = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(UpperCAmelCase_ ): lowerCamelCase_ = int(UpperCAmelCase_ ) total_partitions += 1 if check_partition_perfect(UpperCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(UpperCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f'''{solution() = }''')
55
1
from __future__ import annotations def snake_case (A_ :str , A_ :list[str] | None = None , A_ :dict[str, float] | None = None , A_ :bool = False , ): '''simple docstring''' a : Dict = cipher_alphabet or [chr(A_ ) for i in range(9_7 , 1_2_3 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) a : Optional[int] = { 'a': 0.0_8497, 'b': 0.0_1492, 'c': 0.0_2202, 'd': 0.0_4253, 'e': 0.1_1162, 'f': 0.0_2228, 'g': 0.0_2015, 'h': 0.0_6094, 'i': 0.0_7546, 'j': 0.0_0153, 'k': 0.0_1292, 'l': 0.0_4025, 'm': 0.0_2406, 'n': 0.0_6749, 'o': 0.0_7507, 'p': 0.0_1929, 'q': 0.0_0095, 'r': 0.0_7587, 's': 0.0_6327, 't': 0.0_9356, 'u': 0.0_2758, 'v': 0.0_0978, 'w': 0.0_2560, 'x': 0.0_0150, 'y': 0.0_1994, 'z': 0.0_0077, } else: # Custom frequencies dictionary a : Union[str, Any] = frequencies_dict if not case_sensitive: a : Tuple = ciphertext.lower() # Chi squared statistic values a : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(A_ ) ): a : Dict = '' # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet a : Any = (alphabet_letters.index(letter.lower() ) - shift) % len( A_ ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter a : Optional[Any] = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: a : Any = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message a : str = decrypted_with_shift.lower().count(A_ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies a : int = frequencies[letter] * occurrences # Complete the chi squared statistic formula a : List[str] = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message a : Union[str, Any] = decrypted_with_shift.count(A_ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies a : Tuple = frequencies[letter] * occurrences # Complete the chi squared statistic formula a : Dict = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary a : List[Any] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(A_ :int ) -> tuple[float, str]: return chi_squared_statistic_values[key] a : int = min( A_ , key=A_ , ) # Get all the data from the most likely cipher (key, decoded message) ( a ) : List[str] = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
363
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging _UpperCamelCase : int = logging.get_logger(__name__) class snake_case ( UpperCAmelCase ): __magic_name__ = ['''input_features''', '''attention_mask'''] def __init__( self : Optional[int] , A : Optional[Any]=8_0 , A : str=1_6_0_0_0 , A : List[str]=0.0 , A : Any=1_0 , A : Union[str, Any]=2_5 , A : str="hamming_window" , A : str=3_27_68.0 , A : Union[str, Any]=0.97 , A : Dict=1.0 , A : Any=True , A : Union[str, Any]=True , A : List[Any]=False , **A : Tuple , ): '''simple docstring''' super().__init__(feature_size=A , sampling_rate=A , padding_value=A , **A ) a : Any = feature_size a : List[Any] = sampling_rate a : Any = padding_value a : str = hop_length a : Any = win_length a : List[Any] = frame_signal_scale a : Tuple = preemphasis_coeff a : Dict = mel_floor a : Optional[int] = normalize_means a : List[str] = normalize_vars a : Dict = win_function a : Union[str, Any] = return_attention_mask a : List[Any] = win_length * sampling_rate // 1_0_0_0 a : Tuple = hop_length * sampling_rate // 1_0_0_0 a : List[Any] = optimal_fft_length(self.sample_size ) a : Any = (self.n_fft // 2) + 1 def lowerCamelCase__ ( self : List[Any] , A : np.array ): '''simple docstring''' if self.win_function == "hamming_window": a : List[str] = window_function(window_length=self.sample_size , name=self.win_function , periodic=A ) else: a : Dict = window_function(window_length=self.sample_size , name=self.win_function ) a : str = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) a : List[Any] = spectrogram( one_waveform * self.frame_signal_scale , window=A , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=A , preemphasis=self.preemphasis_coeff , mel_filters=A , mel_floor=self.mel_floor , log_mel='log' , ) return msfc_features.T def lowerCamelCase__ ( self : int , A : Tuple , A : int , A : Optional[int] ): '''simple docstring''' if self.normalize_means: a : Any = x[:input_length].mean(axis=0 ) a : Dict = np.subtract(A , A ) if self.normalize_vars: a : Dict = x[:input_length].std(axis=0 ) a : Dict = np.divide(A , A ) if input_length < x.shape[0]: a : Dict = padding_value # make sure array is in float32 a : Optional[int] = x.astype(np.floataa ) return x def lowerCamelCase__ ( self : str , A : List[np.ndarray] , A : Optional[np.ndarray] = None ): '''simple docstring''' a : str = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(A , A , self.padding_value ) for x, n in zip(A , A )] def __call__( self : Dict , A : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , A : Union[bool, str, PaddingStrategy] = False , A : Optional[int] = None , A : bool = False , A : Optional[int] = None , A : Optional[bool] = None , A : Optional[Union[str, TensorType]] = None , A : Optional[int] = None , **A : Union[str, Any] , ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' F''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' F''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( 'It is strongly recommended to pass the ``sampling_rate`` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) a : Optional[int] = isinstance(A , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' ) a : Dict = is_batched_numpy or ( isinstance(A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: a : str = [np.asarray(A , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(A , np.ndarray ): a : List[str] = np.asarray(A , dtype=np.floataa ) elif isinstance(A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a : Optional[int] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: a : Any = [raw_speech] # extract fbank features a : str = [self._extract_mfsc_features(A ) for one_waveform in raw_speech] # convert into correct format for padding a : int = BatchFeature({'input_features': features} ) a : Union[str, Any] = self.pad( A , padding=A , max_length=A , truncation=A , pad_to_multiple_of=A , return_attention_mask=A , **A , ) # make sure list is in array format a : Optional[Any] = padded_inputs.get('input_features' ) if isinstance(input_features[0] , A ): a : List[str] = [np.asarray(A , dtype=np.floataa ) for feature in input_features] a : List[Any] = padded_inputs.get('attention_mask' ) if attention_mask is not None: a : int = [np.asarray(A , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: a : Any = ( np.array(A , dtype=np.intaa ) if self._get_padding_strategies(A , max_length=A ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) a : List[str] = self.normalize( padded_inputs['input_features'] , attention_mask=A ) if return_tensors is not None: a : Optional[int] = padded_inputs.convert_to_tensors(A ) return padded_inputs
186
0
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[Any] ,snake_case : Optional[Any] ,snake_case : Optional[Any]=13 ,snake_case : List[Any]=30 ,snake_case : Optional[Any]=2 ,snake_case : Optional[int]=3 ,snake_case : int=True ,snake_case : Optional[Any]=True ,snake_case : List[str]=32 ,snake_case : str=2 ,snake_case : str=4 ,snake_case : int=37 ,snake_case : Tuple="gelu" ,snake_case : Any=0.1 ,snake_case : int=0.1 ,snake_case : str=10 ,snake_case : List[str]=0.02 ,snake_case : int=3 ,snake_case : List[Any]=None ,snake_case : int=2 ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 2 def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels def _lowerCAmelCase ( self : Optional[Any] ): return DeiTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=A_ ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def _lowerCAmelCase ( self : Dict ,snake_case : Any ,snake_case : Any ,snake_case : int ): SCREAMING_SNAKE_CASE =TFDeiTModel(config=A_ ) SCREAMING_SNAKE_CASE =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =TFDeiTForMaskedImageModeling(config=A_ ) SCREAMING_SNAKE_CASE =model(A_ ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =TFDeiTForMaskedImageModeling(A_ ) SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(A_ ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Union[str, Any] ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =TFDeiTForImageClassification(A_ ) SCREAMING_SNAKE_CASE =model(A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =TFDeiTForImageClassification(A_ ) SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =config_and_inputs SCREAMING_SNAKE_CASE ={'pixel_values': pixel_values} return config, inputs_dict @require_tf class a_ ( _lowercase , _lowercase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __UpperCAmelCase = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =TFDeiTModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(A_ ) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(A_ ,tf.keras.layers.Dense ) ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(A_ ) SCREAMING_SNAKE_CASE =inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE =['pixel_values'] self.assertListEqual(arg_names[:1] ,A_ ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A_ ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) def _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Any ,snake_case : List[Any]=False ): SCREAMING_SNAKE_CASE =super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def _lowerCAmelCase ( self : List[Any] ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =TFDeiTModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=A_ ,return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE =model(**A_ ) # verify the logits SCREAMING_SNAKE_CASE =tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape ,A_ ) SCREAMING_SNAKE_CASE =tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] ,A_ ,atol=1e-4 ) )
334
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''roformer''' def __init__( self : Tuple ,A_ : Optional[int]=5_0000 ,A_ : Tuple=None ,A_ : Optional[Any]=768 ,A_ : Dict=12 ,A_ : Optional[int]=12 ,A_ : Union[str, Any]=3072 ,A_ : Dict="gelu" ,A_ : Dict=0.1 ,A_ : List[Any]=0.1 ,A_ : List[Any]=1536 ,A_ : List[str]=2 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : Optional[int]=0 ,A_ : List[str]=False ,A_ : Tuple=True ,**A_ : List[str] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size if embedding_size is None else embedding_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = rotary_value A = use_cache class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
74
0
'''simple docstring''' import re from filelock import FileLock try: import nltk _lowercase : Any = True except (ImportError, ModuleNotFoundError): _lowercase : Union[str, Any] = False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def lowerCamelCase ( UpperCAmelCase__ : str ) -> str: re.sub("""<n>""" , """""" , UpperCAmelCase__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCAmelCase__ ) )
21
'''simple docstring''' from __future__ import annotations from typing import Any def lowerCamelCase ( UpperCAmelCase__ : list ) -> int: if not postfix_notation: return 0 lowercase_ : Any = {"""+""", """-""", """*""", """/"""} lowercase_ : list[Any] = [] for token in postfix_notation: if token in operations: lowercase_ , lowercase_ : Dict = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(UpperCAmelCase__ ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
21
1
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class _UpperCamelCase ( __A , __A ): '''simple docstring''' lowerCamelCase__ =1 @register_to_config def __init__( self : Dict , a : int = 1000 , a : Optional[Union[np.ndarray, List[float]]] = None ) -> Any: """simple docstring""" self.set_timesteps(a ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : int = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : str = 4 # running values SCREAMING_SNAKE_CASE : Optional[int] = [] def __UpperCamelCase ( self : Tuple , a : int , a : Union[str, torch.device] = None ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = num_inference_steps SCREAMING_SNAKE_CASE : Tuple = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Dict = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Tuple = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Any = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : List[Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : Optional[Any] = timesteps.to(a ) SCREAMING_SNAKE_CASE : str = [] def __UpperCamelCase ( self : int , a : torch.FloatTensor , a : int , a : torch.FloatTensor , a : bool = True , ) -> Union[SchedulerOutput, Tuple]: """simple docstring""" if self.num_inference_steps is None: raise ValueError( "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" ) SCREAMING_SNAKE_CASE : Dict = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Tuple = timestep_index + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(a ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : List[Any] = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Tuple = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : int = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Optional[int] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : List[str] = self._get_prev_sample(a , a , a , a ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=a ) def __UpperCamelCase ( self : Optional[int] , a : torch.FloatTensor , *a : Union[str, Any] , **a : Union[str, Any] ) -> torch.FloatTensor: """simple docstring""" return sample def __UpperCamelCase ( self : List[Any] , a : str , a : Tuple , a : Any , a : Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : Any = self.betas[timestep_index] SCREAMING_SNAKE_CASE : str = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : str = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : List[Any] = (sample - sigma * ets) / max(a , 1e-8 ) SCREAMING_SNAKE_CASE : Optional[int] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" return self.config.num_train_timesteps
76
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str ): """simple docstring""" _snake_case : Optional[Any] = list(snake_case__ ) _snake_case : List[Any] = list(snake_case__ ) _snake_case : List[Any] = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count += 1 _snake_case : Any = """_""" if count > 1: return False else: return "".join(snake_case__ ) def UpperCAmelCase__ (snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [] while True: _snake_case : Union[str, Any] = ["""$"""] * len(snake_case__ ) _snake_case : int = [] for i in range(len(snake_case__ ) ): for j in range(i + 1 , len(snake_case__ ) ): _snake_case : List[Any] = compare_string(binary[i] , binary[j] ) if k is False: _snake_case : Dict = """*""" _snake_case : List[Any] = """*""" temp.append("""X""" ) for i in range(len(snake_case__ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case__ ) == 0: return pi _snake_case : Optional[int] = list(set(snake_case__ ) ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : Sequence[float] ): """simple docstring""" _snake_case : Optional[int] = [] for minterm in minterms: _snake_case : Any = """""" for _ in range(snake_case__ ): _snake_case : Optional[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case__ ) return temp def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : int ): """simple docstring""" _snake_case : Dict = list(snake_case__ ) _snake_case : List[str] = list(snake_case__ ) _snake_case : Tuple = 0 for i in range(len(snake_case__ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCAmelCase__ (snake_case__ : list[list[int]] , snake_case__ : list[str] ): """simple docstring""" _snake_case : Any = [] _snake_case : Union[str, Any] = [0] * len(snake_case__ ) for i in range(len(chart[0] ) ): _snake_case : Tuple = 0 _snake_case : str = -1 for j in range(len(snake_case__ ) ): if chart[j][i] == 1: count += 1 _snake_case : Union[str, Any] = j if count == 1: _snake_case : Union[str, Any] = 1 for i in range(len(snake_case__ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case__ ) ): _snake_case : List[Any] = 0 temp.append(prime_implicants[i] ) while True: _snake_case : Optional[int] = 0 _snake_case : str = -1 _snake_case : Any = 0 for i in range(len(snake_case__ ) ): _snake_case : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _snake_case : Dict = count_n _snake_case : Dict = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case__ ) ): _snake_case : Optional[Any] = 0 def UpperCAmelCase__ (snake_case__ : list[str] , snake_case__ : list[str] ): """simple docstring""" _snake_case : int = [[0 for x in range(len(snake_case__ ) )] for x in range(len(snake_case__ ) )] for i in range(len(snake_case__ ) ): _snake_case : Any = prime_implicants[i].count("""_""" ) for j in range(len(snake_case__ ) ): if is_for_table(prime_implicants[i] , binary[j] , snake_case__ ): _snake_case : Tuple = 1 return chart def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = int(input("""Enter the no. of variables\n""" ) ) _snake_case : List[str] = [ float(snake_case__ ) for x in input( """Enter the decimal representation of Minterms 'Spaces Separated'\n""" ).split() ] _snake_case : List[str] = decimal_to_binary(snake_case__ , snake_case__ ) _snake_case : str = check(snake_case__ ) print("""Prime Implicants are:""" ) print(snake_case__ ) _snake_case : int = prime_implicant_chart(snake_case__ , snake_case__ ) _snake_case : str = selection(snake_case__ , snake_case__ ) print("""Essential Prime Implicants are:""" ) print(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
64
0
import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict __A : List[str] = namedtuple( '_TestCommandArgs', [ 'dataset', 'name', 'cache_dir', 'data_dir', 'all_configs', 'save_infos', 'ignore_verifications', 'force_redownload', 'clear_cache', ], defaults=[None, None, None, False, False, False, False, False], ) def __UpperCamelCase ( _A : Any , _A : Tuple ) ->int: """simple docstring""" return (abs(source - target ) / target) < 0.0_1 @pytest.mark.integration def __UpperCamelCase ( _A : Optional[Any] ) ->List[Any]: """simple docstring""" lowerCamelCase_ =_TestCommandArgs(dataset=_A , all_configs=_A , save_infos=_A ) lowerCamelCase_ =TestCommand(*_A ) test_command.run() lowerCamelCase_ =os.path.join(_A , """README.md""" ) assert os.path.exists(_A ) lowerCamelCase_ =DatasetInfosDict.from_directory(_A ) lowerCamelCase_ =DatasetInfosDict( { """default""": DatasetInfo( features=Features( { """tokens""": Sequence(Value("""string""" ) ), """ner_tags""": Sequence( ClassLabel(names=["""O""", """B-PER""", """I-PER""", """B-ORG""", """I-ORG""", """B-LOC""", """I-LOC"""] ) ), """langs""": Sequence(Value("""string""" ) ), """spans""": Sequence(Value("""string""" ) ), } ) , splits=[ { """name""": """train""", """num_bytes""": 2351563, """num_examples""": 10000, }, { """name""": """validation""", """num_bytes""": 238418, """num_examples""": 1000, }, ] , download_size=3940680 , dataset_size=2589981 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: lowerCamelCase_ , lowerCamelCase_ =getattr(dataset_infos["""default"""] , _A ), getattr(expected_dataset_infos["""default"""] , _A ) if key == "num_bytes": assert is_apercent_close(_A , _A ) elif key == "splits": assert list(_A ) == list(_A ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
49
import math def __UpperCamelCase ( _A : int = 100 ) ->int: """simple docstring""" lowerCamelCase_ =sum(i * i for i in range(1 , n + 1 ) ) lowerCamelCase_ =int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
49
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =["""image_processor""", """tokenizer"""] __UpperCAmelCase : Optional[Any] ="""CLIPImageProcessor""" __UpperCAmelCase : Union[str, Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): __lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) __lowerCAmelCase = kwargs.pop("feature_extractor" ) __lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self , __a=None , __a=None , __a=None , **__a ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __lowerCAmelCase = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: __lowerCAmelCase = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: __lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): __lowerCAmelCase = self.tokenizer.model_input_names __lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
57
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( _UpperCamelCase = 4 ): '''simple docstring''' __lowerCAmelCase = abs(_UpperCamelCase ) or 4 return [[1 + x + y * row_size for x in range(_UpperCamelCase )] for y in range(_UpperCamelCase )] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(reverse_column(_UpperCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_column(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [list(_UpperCamelCase ) for x in zip(*_UpperCamelCase )] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = matrix[::-1] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [x[::-1] for x in matrix] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for i in matrix: print(*_UpperCamelCase ) if __name__ == "__main__": A : Dict = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_aa(matrix)) A : List[str] = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_aaa(matrix)) A : str = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_aaa(matrix))
57
1
"""simple docstring""" from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
355
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __snake_case = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class _lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = True , ) -> Tuple: '''simple docstring''' snake_case : List[Any] = [file for file in os.listdir(UpperCamelCase__ ) if os.path.isfile(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) )] if identifier is not None: snake_case : Optional[Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(UpperCamelCase__ , UpperCamelCase__ ): for n_ in n_identifier: snake_case : str = [file for file in files if n_ not in file] else: snake_case : str = [file for file in files if n_identifier not in file] snake_case : Tuple = ignore_files or [] ignore_files.append("__init__.py" ) snake_case : Optional[Any] = [file for file in files if file not in ignore_files] for file in files: # Open all files print("Testing" , UpperCamelCase__ ) if only_modules: snake_case : str = file.split("." )[0] try: snake_case : Optional[int] = getattr(UpperCamelCase__ , UpperCamelCase__ ) snake_case : str = doctest.DocTestSuite(UpperCamelCase__ ) snake_case : Optional[Any] = unittest.TextTestRunner().run(UpperCamelCase__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: snake_case : Tuple = doctest.testfile(str(".." / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def lowerCamelCase ( self ) -> str: '''simple docstring''' snake_case : Tuple = Path("src/transformers" ) snake_case : List[Any] = "modeling" snake_case : Dict = [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(UpperCamelCase__ , identifier=UpperCamelCase__ , ignore_files=UpperCamelCase__ ) def lowerCamelCase ( self ) -> Dict: '''simple docstring''' snake_case : Optional[Any] = Path("src/transformers" ) snake_case : Optional[Any] = "tokenization" self.analyze_directory(UpperCamelCase__ , identifier=UpperCamelCase__ ) def lowerCamelCase ( self ) -> List[str]: '''simple docstring''' snake_case : Union[str, Any] = Path("src/transformers" ) snake_case : Optional[Any] = "configuration" self.analyze_directory(UpperCamelCase__ , identifier=UpperCamelCase__ ) def lowerCamelCase ( self ) -> Optional[Any]: '''simple docstring''' snake_case : List[str] = Path("src/transformers" ) snake_case : List[str] = ["configuration", "modeling", "tokenization"] self.analyze_directory(UpperCamelCase__ , n_identifier=UpperCamelCase__ ) def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' snake_case : Any = Path("docs/source" ) snake_case : Tuple = ["favicon.ico"] self.analyze_directory(UpperCamelCase__ , ignore_files=UpperCamelCase__ , only_modules=UpperCamelCase__ )
112
0
"""simple docstring""" from math import sqrt def snake_case_ ( A_ : int = 1_00_00_00 ): '''simple docstring''' _lowerCamelCase : int = 0 _lowerCamelCase : int = 0 _lowerCamelCase : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2, 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(a_, sum_shortest_sides // 2 ) - max(1, sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(F"""{solution() = }""")
72
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __a = logging.get_logger(__name__) class A__ ( UpperCamelCase ): """simple docstring""" UpperCamelCase_ : Optional[int] = ['''input_features''', '''attention_mask'''] def __init__( self : List[Any] , lowerCAmelCase__ : Union[str, Any]=8_0 , lowerCAmelCase__ : Tuple=1_6_0_0_0 , lowerCAmelCase__ : Union[str, Any]=8_0 , lowerCAmelCase__ : List[Any]=0.0 , lowerCAmelCase__ : str=True , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : List[Any]=True , **lowerCAmelCase__ : int , ) -> int: """simple docstring""" super().__init__(feature_size=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , padding_value=lowerCAmelCase__ , **lowerCAmelCase__ ) _UpperCAmelCase : str = num_mel_bins _UpperCAmelCase : Optional[int] = do_ceptral_normalize _UpperCAmelCase : List[str] = normalize_means _UpperCAmelCase : str = normalize_vars _UpperCAmelCase : Union[str, Any] = True def _lowerCAmelCase ( self : Any , lowerCAmelCase__ : np.ndarray , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase : Tuple = waveform * (2**1_5) # Kaldi compliance: 16-bit signed integers _UpperCAmelCase : Optional[Any] = torch.from_numpy(lowerCAmelCase__ ).unsqueeze(0 ) _UpperCAmelCase : List[Any] = ta_kaldi.fbank(lowerCAmelCase__ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _lowerCAmelCase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : float = 0.0 , ) -> np.ndarray: """simple docstring""" if normalize_means: _UpperCAmelCase : Optional[Any] = x[:input_length].mean(axis=0 ) _UpperCAmelCase : Dict = np.subtract(lowerCAmelCase__ , lowerCAmelCase__ ) if normalize_vars: _UpperCAmelCase : Any = x[:input_length].std(axis=0 ) _UpperCAmelCase : Optional[int] = np.divide(lowerCAmelCase__ , lowerCAmelCase__ ) if input_length < x.shape[0]: _UpperCAmelCase : str = padding_value # make sure array is in float32 _UpperCAmelCase : Union[str, Any] = x.astype(np.floataa ) return x def _lowerCAmelCase ( self : Dict , lowerCAmelCase__ : List[np.ndarray] , lowerCAmelCase__ : Optional[np.ndarray] = None ) -> List[np.ndarray]: """simple docstring""" _UpperCAmelCase : Tuple = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(lowerCAmelCase__ , lowerCAmelCase__ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(lowerCAmelCase__ , lowerCAmelCase__ ) ] def __call__( self : List[Any] , lowerCAmelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCAmelCase__ : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : bool = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[bool] = None , **lowerCAmelCase__ : Optional[Any] , ) -> BatchFeature: """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" F""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" F""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) _UpperCAmelCase : Any = isinstance(lowerCAmelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" ) _UpperCAmelCase : List[Any] = is_batched_numpy or ( isinstance(lowerCAmelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: _UpperCAmelCase : Any = [np.asarray(lowerCAmelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(lowerCAmelCase__ , np.ndarray ): _UpperCAmelCase : Dict = np.asarray(lowerCAmelCase__ , dtype=np.floataa ) elif isinstance(lowerCAmelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): _UpperCAmelCase : Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: _UpperCAmelCase : List[Any] = [raw_speech] # extract fbank features _UpperCAmelCase : Tuple = [self._extract_fbank_features(lowerCAmelCase__ ) for waveform in raw_speech] # convert into correct format for padding _UpperCAmelCase : Optional[Any] = BatchFeature({"input_features": features} ) _UpperCAmelCase : Optional[Any] = self.pad( lowerCAmelCase__ , padding=lowerCAmelCase__ , max_length=lowerCAmelCase__ , truncation=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) # make sure list is in array format _UpperCAmelCase : Optional[Any] = padded_inputs.get("input_features" ) if isinstance(input_features[0] , lowerCAmelCase__ ): _UpperCAmelCase : int = [np.asarray(lowerCAmelCase__ , dtype=np.floataa ) for feature in input_features] _UpperCAmelCase : Optional[int] = padded_inputs.get("attention_mask" ) if attention_mask is not None: _UpperCAmelCase : Dict = [np.asarray(lowerCAmelCase__ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: _UpperCAmelCase : List[str] = ( np.array(lowerCAmelCase__ , dtype=np.intaa ) if self._get_padding_strategies(lowerCAmelCase__ , max_length=lowerCAmelCase__ ) is not PaddingStrategy.DO_NOT_PAD else None ) _UpperCAmelCase : str = self.normalize( padded_inputs["input_features"] , attention_mask=lowerCAmelCase__ ) if return_tensors is not None: _UpperCAmelCase : Any = padded_inputs.convert_to_tensors(lowerCAmelCase__ ) return padded_inputs
145
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a : Union[str, Any] = logging.get_logger(__name__) a : Optional[int] = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __UpperCamelCase ( a__ ): lowerCamelCase : Tuple ="""gpt_neox""" def __init__( self , lowerCAmelCase__=5_0432 , lowerCAmelCase__=6144 , lowerCAmelCase__=44 , lowerCAmelCase__=64 , lowerCAmelCase__=2_4576 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.25 , lowerCAmelCase__=1_0000 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__=2048 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=True , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=None , **lowerCAmelCase__ , ) -> Tuple: super().__init__(bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a : Union[str, Any] = vocab_size a : Optional[Any] = max_position_embeddings a : List[str] = hidden_size a : Dict = num_hidden_layers a : Union[str, Any] = num_attention_heads a : Tuple = intermediate_size a : Optional[int] = hidden_act a : Optional[int] = rotary_pct a : List[str] = rotary_emb_base a : Dict = attention_dropout a : Union[str, Any] = hidden_dropout a : Tuple = classifier_dropout a : Dict = initializer_range a : List[str] = layer_norm_eps a : str = use_cache a : Optional[int] = tie_word_embeddings a : Tuple = use_parallel_residual a : Optional[int] = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( "The hidden size is not divisble by the number of attention heads! Make sure to update them!" ) def __a ( self ) -> Union[str, Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , lowerCAmelCase__ ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f"""got {self.rope_scaling}""" ) a : str = self.rope_scaling.get("type" , lowerCAmelCase__ ) a : Optional[Any] = self.rope_scaling.get("factor" , lowerCAmelCase__ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" ) if rope_scaling_factor is None or not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or rope_scaling_factor <= 1.0: raise ValueError(f"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
79
"""simple docstring""" import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def _SCREAMING_SNAKE_CASE ( _lowercase : List[Any] ) ->Union[str, Any]: '''simple docstring''' if isinstance(_lowercase , collections.abc.Iterable ): return x return (x, x) @require_flax class __UpperCamelCase : def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: pass def __a ( self ) -> List[Any]: pass def __a ( self ) -> str: pass def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Any: a : Dict = np.abs((a - b) ).max() self.assertLessEqual(lowerCAmelCase__ , lowerCAmelCase__ , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> Dict: a : Dict = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase__ , lowerCAmelCase__ ) a : List[str] = FlaxVisionTextDualEncoderModel(lowerCAmelCase__ ) a : int = model(input_ids=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> Optional[Any]: a, a : Optional[int] = self.get_vision_text_model(lowerCAmelCase__ , lowerCAmelCase__ ) a : Dict = {"vision_model": vision_model, "text_model": text_model} a : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase__ ) a : List[str] = model(input_ids=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> Union[str, Any]: a, a : Dict = self.get_vision_text_model(lowerCAmelCase__ , lowerCAmelCase__ ) a : Tuple = {"vision_model": vision_model, "text_model": text_model} a : Tuple = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase__ ) a : List[str] = model(input_ids=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ ) a : Any = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowerCAmelCase__ ) a : str = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase__ ) a : Dict = model(input_ids=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ ) a : List[Any] = after_output[0] a : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowerCAmelCase__ , 1E-3 ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> List[Any]: a, a : Union[str, Any] = self.get_vision_text_model(lowerCAmelCase__ , lowerCAmelCase__ ) a : List[Any] = {"vision_model": vision_model, "text_model": text_model} a : int = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase__ ) a : Tuple = model( input_ids=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , output_attentions=lowerCAmelCase__ ) a : int = output.vision_model_output.attentions self.assertEqual(len(lowerCAmelCase__ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) a : Optional[int] = to_atuple(vision_model.config.image_size ) a : Tuple = to_atuple(vision_model.config.patch_size ) a : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) a : Dict = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) a : str = output.text_model_output.attentions self.assertEqual(len(lowerCAmelCase__ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: pt_model.to(lowerCAmelCase__ ) pt_model.eval() # prepare inputs a : List[Any] = inputs_dict a : Any = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): a : int = pt_model(**lowerCAmelCase__ ).to_tuple() a : Union[str, Any] = fx_model(**lowerCAmelCase__ ).to_tuple() self.assertEqual(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowerCAmelCase__ , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(lowerCAmelCase__ ) a : Dict = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase__ , from_pt=lowerCAmelCase__ ) a : Optional[int] = fx_model_loaded(**lowerCAmelCase__ ).to_tuple() self.assertEqual(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowerCAmelCase__ , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(lowerCAmelCase__ ) a : Optional[int] = VisionTextDualEncoderModel.from_pretrained(lowerCAmelCase__ , from_flax=lowerCAmelCase__ ) pt_model_loaded.to(lowerCAmelCase__ ) pt_model_loaded.eval() with torch.no_grad(): a : int = pt_model_loaded(**lowerCAmelCase__ ).to_tuple() self.assertEqual(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(lowerCAmelCase__ , pt_output_loaded.numpy() , 4E-2 ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[Any]: a : List[Any] = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase__ , lowerCAmelCase__ ) a : Dict = VisionTextDualEncoderModel(lowerCAmelCase__ ) a : Optional[int] = FlaxVisionTextDualEncoderModel(lowerCAmelCase__ ) a : Dict = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , lowerCAmelCase__ ) a : List[str] = fx_state self.check_pt_flax_equivalence(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: a : Optional[int] = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase__ , lowerCAmelCase__ ) a : Optional[int] = VisionTextDualEncoderModel(lowerCAmelCase__ ) a : List[Any] = FlaxVisionTextDualEncoderModel(lowerCAmelCase__ ) a : int = load_flax_weights_in_pytorch_model(lowerCAmelCase__ , fx_model.params ) self.check_pt_flax_equivalence(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def __a ( self ) -> Dict: a : Any = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowerCAmelCase__ ) def __a ( self ) -> Dict: a : List[str] = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowerCAmelCase__ ) def __a ( self ) -> List[str]: a : int = self.prepare_config_and_inputs() self.check_save_load(**lowerCAmelCase__ ) def __a ( self ) -> List[str]: a : Tuple = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowerCAmelCase__ ) @is_pt_flax_cross_test def __a ( self ) -> Any: a : List[Any] = self.prepare_config_and_inputs() a : Tuple = config_inputs_dict.pop("vision_config" ) a : int = config_inputs_dict.pop("text_config" ) a : List[str] = config_inputs_dict self.check_equivalence_pt_to_flax(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) self.check_equivalence_flax_to_pt(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) @slow def __a ( self ) -> List[Any]: a, a : Optional[int] = self.get_pretrained_model_and_inputs() a : Optional[int] = model_a(**lowerCAmelCase__ ) a : Optional[int] = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowerCAmelCase__ ) a : Any = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase__ ) a : str = model_a(**lowerCAmelCase__ ) a : Dict = after_outputs[0] a : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowerCAmelCase__ , 1E-5 ) @require_flax class __UpperCamelCase ( a__ , unittest.TestCase ): def __a ( self ) -> List[Any]: a : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-bert" , vision_from_pt=lowerCAmelCase__ , text_from_pt=lowerCAmelCase__ , ) a : Any = 13 a : str = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a : str = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) a : Optional[Any] = random_attention_mask([batch_size, 4] ) a : Optional[Any] = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: a : Dict = FlaxViTModel(lowerCAmelCase__ ) a : Dict = FlaxBertModel(lowerCAmelCase__ ) return vision_model, text_model def __a ( self ) -> str: a : Union[str, Any] = FlaxViTModelTester(self ) a : Dict = FlaxBertModelTester(self ) a : str = vit_model_tester.prepare_config_and_inputs() a : Any = bert_model_tester.prepare_config_and_inputs() a, a : Optional[int] = vision_config_and_inputs a, a, a, a : Dict = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class __UpperCamelCase ( a__ , unittest.TestCase ): def __a ( self ) -> List[Any]: a : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-clip" , "hf-internal-testing/tiny-bert" , vision_from_pt=lowerCAmelCase__ , text_from_pt=lowerCAmelCase__ , ) a : Tuple = 13 a : Union[str, Any] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a : Union[str, Any] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) a : Tuple = random_attention_mask([batch_size, 4] ) a : str = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: a : List[Any] = FlaxCLIPVisionModel(lowerCAmelCase__ ) a : Tuple = FlaxBertModel(lowerCAmelCase__ ) return vision_model, text_model def __a ( self ) -> List[Any]: a : Tuple = FlaxCLIPVisionModelTester(self ) a : Union[str, Any] = FlaxBertModelTester(self ) a : Dict = clip_model_tester.prepare_config_and_inputs() a : Optional[int] = bert_model_tester.prepare_config_and_inputs() a, a : Dict = vision_config_and_inputs a, a, a, a : Union[str, Any] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class __UpperCamelCase ( unittest.TestCase ): @slow def __a ( self ) -> Dict: a : str = FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian" , logit_scale_init_value=1.0 ) a : Optional[Any] = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) a : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) a : Optional[int] = processor( text=["una foto di un gatto", "una foto di un cane"] , images=lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors="np" ) a : Optional[Any] = model(**lowerCAmelCase__ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) a : List[str] = np.array([[1.2_284_727, 0.3_104_122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , lowerCAmelCase__ , atol=1E-3 ) )
79
1
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowercase_ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): __UpperCAmelCase = RoCBertTokenizer __UpperCAmelCase = None __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = filter_non_english def __a ( self ): super().setUp() UpperCamelCase__ = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] UpperCamelCase__ = {} UpperCamelCase__ = {} for i, value in enumerate(A__ ): UpperCamelCase__ = i UpperCamelCase__ = i UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(A__ , A__ , ensure_ascii=A__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(A__ , A__ , ensure_ascii=A__ ) def __a ( self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase__ = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(A__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(A__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(A__ ) , [5, 6, 2, 5, 7, 8] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def __a ( self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=A__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def __a ( self ): UpperCamelCase__ = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] UpperCamelCase__ = {} for i, token in enumerate(A__ ): UpperCamelCase__ = i UpperCamelCase__ = RoCBertWordpieceTokenizer(vocab=A__ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def __a ( self ): self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def __a ( self ): self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def __a ( self ): self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def __a ( self ): UpperCamelCase__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(A__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: UpperCamelCase__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(A__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) UpperCamelCase__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' UpperCamelCase__ = tokenizer_r.encode_plus( A__ , return_attention_mask=A__ , return_token_type_ids=A__ , return_offsets_mapping=A__ , add_special_tokens=A__ , ) UpperCamelCase__ = tokenizer_r.do_lower_case if hasattr(A__ , "do_lower_case" ) else False UpperCamelCase__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def __a ( self ): UpperCamelCase__ = ["的", "人", "有"] UpperCamelCase__ = "".join(A__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = True UpperCamelCase__ = self.tokenizer_class.from_pretrained(A__ , **A__ ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) UpperCamelCase__ = tokenizer_p.encode(A__ , add_special_tokens=A__ ) UpperCamelCase__ = tokenizer_r.encode(A__ , add_special_tokens=A__ ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(A__ ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(A__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(A__ , A__ ) self.assertListEqual(A__ , A__ ) UpperCamelCase__ = False UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(A__ , **A__ ) UpperCamelCase__ = tokenizer_r.encode(A__ , add_special_tokens=A__ ) UpperCamelCase__ = tokenizer_p.encode(A__ , add_special_tokens=A__ ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(A__ ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(A__ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCamelCase__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(A__ ) ] self.assertListEqual(A__ , A__ ) self.assertListEqual(A__ , A__ ) @slow def __a ( self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase__ = tokenizer.encode("你好" , add_special_tokens=A__ ) UpperCamelCase__ = tokenizer.encode("你是谁" , add_special_tokens=A__ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(A__ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(A__ , A__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __a ( self ): UpperCamelCase__ = self.get_tokenizers(do_lower_case=A__ ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): UpperCamelCase__ = "你好,你是谁" UpperCamelCase__ = tokenizer.tokenize(A__ ) UpperCamelCase__ = tokenizer.convert_tokens_to_ids(A__ ) UpperCamelCase__ = tokenizer.convert_tokens_to_shape_ids(A__ ) UpperCamelCase__ = tokenizer.convert_tokens_to_pronunciation_ids(A__ ) UpperCamelCase__ = tokenizer.prepare_for_model( A__ , A__ , A__ , add_special_tokens=A__ ) UpperCamelCase__ = tokenizer.encode_plus(A__ , add_special_tokens=A__ ) self.assertEqual(A__ , A__ )
80
from __future__ import annotations lowercase__ :Any = 1.60_21E-19 # units = C def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ): '''simple docstring''' 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()
101
0
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = {"vocab_file": "spiece.model"} lowerCAmelCase_ = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } lowerCAmelCase_ = { "albert-base-v1": 5_1_2, "albert-large-v1": 5_1_2, "albert-xlarge-v1": 5_1_2, "albert-xxlarge-v1": 5_1_2, "albert-base-v2": 5_1_2, "albert-large-v2": 5_1_2, "albert-xlarge-v2": 5_1_2, "albert-xxlarge-v2": 5_1_2, } lowerCAmelCase_ = "▁" class lowerCamelCase ( __lowerCAmelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self, lowercase_, lowercase_=True, lowercase_=True, lowercase_=False, lowercase_="[CLS]", lowercase_="[SEP]", lowercase_="<unk>", lowercase_="[SEP]", lowercase_="<pad>", lowercase_="[CLS]", lowercase_="[MASK]", lowercase_ = None, **lowercase_, ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. snake_case = ( AddedToken(lowercase_, lstrip=lowercase_, rstrip=lowercase_, normalized=lowercase_ ) if isinstance(lowercase_, lowercase_ ) else mask_token ) snake_case = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=lowercase_, remove_space=lowercase_, keep_accents=lowercase_, bos_token=lowercase_, eos_token=lowercase_, unk_token=lowercase_, sep_token=lowercase_, pad_token=lowercase_, cls_token=lowercase_, mask_token=lowercase_, sp_model_kwargs=self.sp_model_kwargs, **lowercase_, ) snake_case = do_lower_case snake_case = remove_space snake_case = keep_accents snake_case = vocab_file snake_case = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase_ ) @property def _lowerCamelCase ( self ) -> str: return len(self.sp_model ) def _lowerCamelCase ( self ) -> int: snake_case = {self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> str: snake_case = self.__dict__.copy() snake_case = None return state def __setstate__( self, lowercase_ ) -> Optional[Any]: snake_case = d # for backward compatibility if not hasattr(self, 'sp_model_kwargs' ): snake_case = {} snake_case = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCamelCase ( self, lowercase_ ) -> List[Any]: if self.remove_space: snake_case = ' '.join(inputs.strip().split() ) else: snake_case = inputs snake_case = outputs.replace('``', '"' ).replace('\'\'', '"' ) if not self.keep_accents: snake_case = unicodedata.normalize('NFKD', lowercase_ ) snake_case = ''.join([c for c in outputs if not unicodedata.combining(lowercase_ )] ) if self.do_lower_case: snake_case = outputs.lower() return outputs def _lowerCamelCase ( self, lowercase_ ) -> List[str]: snake_case = self.preprocess_text(lowercase_ ) snake_case = self.sp_model.encode(lowercase_, out_type=lowercase_ ) snake_case = [] for piece in pieces: if len(lowercase_ ) > 1 and piece[-1] == str(',' ) and piece[-2].isdigit(): snake_case = self.sp_model.EncodeAsPieces(piece[:-1].replace(lowercase_, '' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case = cur_pieces[1:] else: snake_case = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(lowercase_ ) else: new_pieces.append(lowercase_ ) return new_pieces def _lowerCamelCase ( self, lowercase_ ) -> int: return self.sp_model.PieceToId(lowercase_ ) def _lowerCamelCase ( self, lowercase_ ) -> Tuple: return self.sp_model.IdToPiece(lowercase_ ) def _lowerCamelCase ( self, lowercase_ ) -> str: snake_case = [] snake_case = '' snake_case = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase_ ) + token snake_case = True snake_case = [] else: current_sub_tokens.append(lowercase_ ) snake_case = False out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def _lowerCamelCase ( self, lowercase_, lowercase_ = None ) -> List[int]: snake_case = [self.sep_token_id] snake_case = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowerCamelCase ( self, lowercase_, lowercase_ = None, lowercase_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_, token_ids_a=lowercase_, already_has_special_tokens=lowercase_ ) if token_ids_a is not None: return [1] + ([0] * len(lowercase_ )) + [1] + ([0] * len(lowercase_ )) + [1] return [1] + ([0] * len(lowercase_ )) + [1] def _lowerCamelCase ( self, lowercase_, lowercase_ = None ) -> List[int]: snake_case = [self.sep_token_id] snake_case = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowerCamelCase ( self, lowercase_, lowercase_ = None ) -> Tuple[str]: if not os.path.isdir(lowercase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return snake_case = os.path.join( lowercase_, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, lowercase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase_, 'wb' ) as fi: snake_case = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
332
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = { "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"], "processing_vision_text_dual_encoder": ["VisionTextDualEncoderProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ["VisionTextDualEncoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ["FlaxVisionTextDualEncoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ["TFVisionTextDualEncoderModel"] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
332
1
from __future__ import annotations def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 2 SCREAMING_SNAKE_CASE : Optional[int] = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_A ) if n > 1: factors.append(_A ) return factors if __name__ == "__main__": import doctest doctest.testmod()
313
'''simple docstring''' def snake_case__ ( _A: int , _A: int ) -> int: '''simple docstring''' while a != 0: lowerCAmelCase , lowerCAmelCase = b % a, a return b def snake_case__ ( _A: int , _A: int ) -> int: '''simple docstring''' if gcd(_A , _A ) != 1: lowerCAmelCase = f"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(_A ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = 1, 0, a lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = 0, 1, m while va != 0: lowerCAmelCase = ua // va lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
272
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , A , A=7 , A=3 , A=1_8 , A=3_0 , A=4_0_0 , A=True , A=None , A=True , ) -> Any: _UpperCAmelCase : Optional[int] = size if size is not None else {'''height''': 1_8, '''width''': 1_8} _UpperCAmelCase : List[Any] = parent _UpperCAmelCase : Tuple = batch_size _UpperCAmelCase : Dict = num_channels _UpperCAmelCase : Union[str, Any] = image_size _UpperCAmelCase : str = min_resolution _UpperCAmelCase : str = max_resolution _UpperCAmelCase : Union[str, Any] = do_resize _UpperCAmelCase : List[Any] = size _UpperCAmelCase : Optional[int] = apply_ocr def __lowerCAmelCase ( self ) -> List[str]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _UpperCAmelCase ( a ,unittest.TestCase ): '''simple docstring''' a__ =LayoutLMvaImageProcessor if is_pytesseract_available() else None def __lowerCAmelCase ( self ) -> int: _UpperCAmelCase : Tuple = LayoutLMvaImageProcessingTester(self ) @property def __lowerCAmelCase ( self ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self ) -> int: _UpperCAmelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A , '''do_resize''' ) ) self.assertTrue(hasattr(A , '''size''' ) ) self.assertTrue(hasattr(A , '''apply_ocr''' ) ) def __lowerCAmelCase ( self ) -> Dict: _UpperCAmelCase : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 1_8, '''width''': 1_8} ) _UpperCAmelCase : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'''height''': 4_2, '''width''': 4_2} ) def __lowerCAmelCase ( self ) -> Union[str, Any]: pass def __lowerCAmelCase ( self ) -> int: # Initialize image_processing _UpperCAmelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A , Image.Image ) # Test not batched input _UpperCAmelCase : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , A ) self.assertIsInstance(encoding.boxes , A ) # Test batched _UpperCAmelCase : Union[str, Any] = image_processing(A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def __lowerCAmelCase ( self ) -> List[str]: # Initialize image_processing _UpperCAmelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , numpify=A ) for image in image_inputs: self.assertIsInstance(A , np.ndarray ) # Test not batched input _UpperCAmelCase : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched _UpperCAmelCase : List[Any] = image_processing(A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def __lowerCAmelCase ( self ) -> Dict: # Initialize image_processing _UpperCAmelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , torchify=A ) for image in image_inputs: self.assertIsInstance(A , torch.Tensor ) # Test not batched input _UpperCAmelCase : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched _UpperCAmelCase : List[Any] = image_processing(A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def __lowerCAmelCase ( self ) -> str: # with apply_OCR = True _UpperCAmelCase : int = LayoutLMvaImageProcessor() from datasets import load_dataset _UpperCAmelCase : Dict = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) _UpperCAmelCase : Optional[Any] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) _UpperCAmelCase : List[Any] = image_processing(A , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 _UpperCAmelCase : Optional[Any] = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 _UpperCAmelCase : Any = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , A ) self.assertListEqual(encoding.boxes , A ) # with apply_OCR = False _UpperCAmelCase : Tuple = LayoutLMvaImageProcessor(apply_ocr=A ) _UpperCAmelCase : List[Any] = image_processing(A , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
68
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class _UpperCAmelCase : '''simple docstring''' def __init__( self ) -> Tuple: _UpperCAmelCase : str = {} def __lowerCAmelCase ( self , A , A , A=1 ) -> Optional[Any]: if self.graph.get(A ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: _UpperCAmelCase : Optional[int] = [[w, v]] if not self.graph.get(A ): _UpperCAmelCase : List[str] = [] def __lowerCAmelCase ( self ) -> Optional[int]: return list(self.graph ) def __lowerCAmelCase ( self , A , A ) -> int: if self.graph.get(A ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A ) def __lowerCAmelCase ( self , A=-2 , A=-1 ) -> Optional[int]: if s == d: return [] _UpperCAmelCase : Any = [] _UpperCAmelCase : Tuple = [] if s == -2: _UpperCAmelCase : List[str] = list(self.graph )[0] stack.append(A ) visited.append(A ) _UpperCAmelCase : Tuple = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: _UpperCAmelCase : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A ) return visited else: stack.append(node[1] ) visited.append(node[1] ) _UpperCAmelCase : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A ) != 0: _UpperCAmelCase : List[str] = stack[len(A ) - 1] else: _UpperCAmelCase : Union[str, Any] = ss # check if se have reached the starting point if len(A ) == 0: return visited def __lowerCAmelCase ( self , A=-1 ) -> List[Any]: if c == -1: _UpperCAmelCase : Optional[int] = floor(random() * 1_0_0_0_0 ) + 1_0 for i in range(A ): # every vertex has max 100 edges for _ in range(floor(random() * 1_0_2 ) + 1 ): _UpperCAmelCase : List[Any] = floor(random() * c ) + 1 if n != i: self.add_pair(A , A , 1 ) def __lowerCAmelCase ( self , A=-2 ) -> Optional[Any]: _UpperCAmelCase : int = deque() _UpperCAmelCase : Optional[int] = [] if s == -2: _UpperCAmelCase : Tuple = list(self.graph )[0] d.append(A ) visited.append(A ) while d: _UpperCAmelCase : int = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __lowerCAmelCase ( self , A ) -> Optional[int]: _UpperCAmelCase : str = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def __lowerCAmelCase ( self , A ) -> int: return len(self.graph[u] ) def __lowerCAmelCase ( self , A=-2 ) -> str: _UpperCAmelCase : int = [] _UpperCAmelCase : Union[str, Any] = [] if s == -2: _UpperCAmelCase : Any = list(self.graph )[0] stack.append(A ) visited.append(A ) _UpperCAmelCase : List[Any] = s _UpperCAmelCase : str = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: _UpperCAmelCase : Optional[int] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) _UpperCAmelCase : str = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(A ) != 0: _UpperCAmelCase : Optional[Any] = stack[len(A ) - 1] else: _UpperCAmelCase : List[str] = ss # check if se have reached the starting point if len(A ) == 0: return sorted_nodes def __lowerCAmelCase ( self ) -> Tuple: _UpperCAmelCase : Union[str, Any] = [] _UpperCAmelCase : Optional[Any] = [] _UpperCAmelCase : Dict = list(self.graph )[0] stack.append(A ) visited.append(A ) _UpperCAmelCase : Union[str, Any] = -2 _UpperCAmelCase : List[str] = [] _UpperCAmelCase : Tuple = s _UpperCAmelCase : Tuple = False _UpperCAmelCase : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: _UpperCAmelCase : int = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): _UpperCAmelCase : Union[str, Any] = len(A ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) _UpperCAmelCase : List[str] = node[1] break # check if all the children are visited if s == ss: stack.pop() _UpperCAmelCase : Tuple = True if len(A ) != 0: _UpperCAmelCase : Union[str, Any] = stack[len(A ) - 1] else: _UpperCAmelCase : Union[str, Any] = False indirect_parents.append(A ) _UpperCAmelCase : Optional[int] = s _UpperCAmelCase : int = ss # check if se have reached the starting point if len(A ) == 0: return list(A ) def __lowerCAmelCase ( self ) -> List[Any]: _UpperCAmelCase : Any = [] _UpperCAmelCase : Tuple = [] _UpperCAmelCase : List[str] = list(self.graph )[0] stack.append(A ) visited.append(A ) _UpperCAmelCase : int = -2 _UpperCAmelCase : Tuple = [] _UpperCAmelCase : Optional[int] = s _UpperCAmelCase : Union[str, Any] = False _UpperCAmelCase : List[str] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: _UpperCAmelCase : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): _UpperCAmelCase : Optional[Any] = len(A ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) _UpperCAmelCase : str = node[1] break # check if all the children are visited if s == ss: stack.pop() _UpperCAmelCase : List[Any] = True if len(A ) != 0: _UpperCAmelCase : int = stack[len(A ) - 1] else: _UpperCAmelCase : List[str] = False indirect_parents.append(A ) _UpperCAmelCase : List[Any] = s _UpperCAmelCase : Any = ss # check if se have reached the starting point if len(A ) == 0: return False def __lowerCAmelCase ( self , A=-2 , A=-1 ) -> Dict: _UpperCAmelCase : Tuple = time() self.dfs(A , A ) _UpperCAmelCase : Optional[int] = time() return end - begin def __lowerCAmelCase ( self , A=-2 ) -> Dict: _UpperCAmelCase : int = time() self.bfs(A ) _UpperCAmelCase : str = time() return end - begin class _UpperCAmelCase : '''simple docstring''' def __init__( self ) -> Optional[int]: _UpperCAmelCase : str = {} def __lowerCAmelCase ( self , A , A , A=1 ) -> str: # check if the u exists if self.graph.get(A ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist _UpperCAmelCase : int = [[w, v]] # add the other way if self.graph.get(A ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist _UpperCAmelCase : List[Any] = [[w, u]] def __lowerCAmelCase ( self , A , A ) -> List[str]: if self.graph.get(A ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A ) # the other way round if self.graph.get(A ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(A ) def __lowerCAmelCase ( self , A=-2 , A=-1 ) -> Any: if s == d: return [] _UpperCAmelCase : Optional[Any] = [] _UpperCAmelCase : Tuple = [] if s == -2: _UpperCAmelCase : Optional[int] = list(self.graph )[0] stack.append(A ) visited.append(A ) _UpperCAmelCase : int = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: _UpperCAmelCase : List[str] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A ) return visited else: stack.append(node[1] ) visited.append(node[1] ) _UpperCAmelCase : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A ) != 0: _UpperCAmelCase : Dict = stack[len(A ) - 1] else: _UpperCAmelCase : Tuple = ss # check if se have reached the starting point if len(A ) == 0: return visited def __lowerCAmelCase ( self , A=-1 ) -> List[str]: if c == -1: _UpperCAmelCase : int = floor(random() * 1_0_0_0_0 ) + 1_0 for i in range(A ): # every vertex has max 100 edges for _ in range(floor(random() * 1_0_2 ) + 1 ): _UpperCAmelCase : Dict = floor(random() * c ) + 1 if n != i: self.add_pair(A , A , 1 ) def __lowerCAmelCase ( self , A=-2 ) -> Tuple: _UpperCAmelCase : List[str] = deque() _UpperCAmelCase : Optional[int] = [] if s == -2: _UpperCAmelCase : Optional[int] = list(self.graph )[0] d.append(A ) visited.append(A ) while d: _UpperCAmelCase : str = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __lowerCAmelCase ( self , A ) -> List[str]: return len(self.graph[u] ) def __lowerCAmelCase ( self ) -> Any: _UpperCAmelCase : str = [] _UpperCAmelCase : Any = [] _UpperCAmelCase : Optional[Any] = list(self.graph )[0] stack.append(A ) visited.append(A ) _UpperCAmelCase : Any = -2 _UpperCAmelCase : Any = [] _UpperCAmelCase : Tuple = s _UpperCAmelCase : Tuple = False _UpperCAmelCase : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: _UpperCAmelCase : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): _UpperCAmelCase : Optional[int] = len(A ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) _UpperCAmelCase : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() _UpperCAmelCase : Dict = True if len(A ) != 0: _UpperCAmelCase : List[str] = stack[len(A ) - 1] else: _UpperCAmelCase : str = False indirect_parents.append(A ) _UpperCAmelCase : Tuple = s _UpperCAmelCase : int = ss # check if se have reached the starting point if len(A ) == 0: return list(A ) def __lowerCAmelCase ( self ) -> Tuple: _UpperCAmelCase : List[Any] = [] _UpperCAmelCase : Union[str, Any] = [] _UpperCAmelCase : str = list(self.graph )[0] stack.append(A ) visited.append(A ) _UpperCAmelCase : Tuple = -2 _UpperCAmelCase : List[Any] = [] _UpperCAmelCase : Any = s _UpperCAmelCase : Dict = False _UpperCAmelCase : List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: _UpperCAmelCase : Dict = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): _UpperCAmelCase : List[str] = len(A ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) _UpperCAmelCase : List[str] = node[1] break # check if all the children are visited if s == ss: stack.pop() _UpperCAmelCase : List[Any] = True if len(A ) != 0: _UpperCAmelCase : Dict = stack[len(A ) - 1] else: _UpperCAmelCase : str = False indirect_parents.append(A ) _UpperCAmelCase : List[Any] = s _UpperCAmelCase : Optional[int] = ss # check if se have reached the starting point if len(A ) == 0: return False def __lowerCAmelCase ( self ) -> int: return list(self.graph ) def __lowerCAmelCase ( self , A=-2 , A=-1 ) -> str: _UpperCAmelCase : List[Any] = time() self.dfs(A , A ) _UpperCAmelCase : Union[str, Any] = time() return end - begin def __lowerCAmelCase ( self , A=-2 ) -> Optional[int]: _UpperCAmelCase : List[Any] = time() self.bfs(A ) _UpperCAmelCase : Optional[int] = time() return end - begin
68
1
import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , a , a=13 , a=30 , a=2 , a=3 , a=True , a=True , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=10 , a=0.02 , ) -> int: snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = is_training snake_case_ = use_labels snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = type_sequence_label_size snake_case_ = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ = (image_size // patch_size) ** 2 snake_case_ = num_patches + 1 def _UpperCamelCase ( self ) -> int: snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a , initializer_range=self.initializer_range , ) return config, pixel_values def _UpperCamelCase ( self , a , a ) -> Any: snake_case_ = FlaxViTModel(config=a ) snake_case_ = model(a ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) snake_case_ = (self.image_size, self.image_size) snake_case_ = (self.patch_size, self.patch_size) snake_case_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def _UpperCamelCase ( self , a , a ) -> Dict: snake_case_ = self.type_sequence_label_size snake_case_ = FlaxViTForImageClassification(config=a ) snake_case_ = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ = 1 snake_case_ = FlaxViTForImageClassification(a ) snake_case_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ = model(a ) def _UpperCamelCase ( self ) -> int: snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class UpperCamelCase_ ( snake_case_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def _UpperCamelCase ( self ) -> None: snake_case_ = FlaxViTModelTester(self ) snake_case_ = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37 ) def _UpperCamelCase ( self ) -> int: self.config_tester.run_common_tests() def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _UpperCamelCase ( self ) -> Tuple: snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) def _UpperCamelCase ( self ) -> Union[str, Any]: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a ) snake_case_ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) def _UpperCamelCase ( self ) -> Union[str, Any]: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case_ = self._prepare_for_class(a , a ) snake_case_ = model_class(a ) @jax.jit def model_jitted(a , **a ): return model(pixel_values=a , **a ) with self.subTest('JIT Enabled' ): snake_case_ = model_jitted(**a ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): snake_case_ = model_jitted(**a ).to_tuple() self.assertEqual(len(a ) , len(a ) ) for jitted_output, output in zip(a , a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def _UpperCamelCase ( self ) -> Dict: for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained('google/vit-base-patch16-224' ) snake_case_ = model(np.ones((1, 3, 2_24, 2_24) ) ) self.assertIsNotNone(a )
178
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowercase = "\\n Text data.\n Second line of data." lowercase = "file" @pytest.fixture(scope='session') def __UpperCAmelCase ( a_): snake_case_ = tmp_path_factory.mktemp('data') / (FILE_PATH + '.zstd') snake_case_ = bytes(a_ , 'utf-8') with zstd.open(a_ , 'wb') as f: f.write(a_) return path @pytest.fixture def __UpperCAmelCase ( a_): with open(os.path.join(tmpfs.local_root_dir , a_) , 'w') as f: f.write(a_) return FILE_PATH @pytest.mark.parametrize('compression_format' , ['gzip', 'xz', 'zstd']) def __UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_): snake_case_ = {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_path} snake_case_ = input_paths[compression_format] snake_case_ = tmp_path / 'cache' snake_case_ = DownloadConfig(cache_dir=a_ , extract_compressed_file=a_) snake_case_ = cached_path(a_ , download_config=a_) with open(a_) as f: snake_case_ = f.read() with open(a_) as f: snake_case_ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize('default_extracted' , [True, False]) @pytest.mark.parametrize('default_cache_dir' , [True, False]) def __UpperCAmelCase ( a_ , a_ , a_ , a_ , a_): snake_case_ = 'custom_cache' snake_case_ = 'custom_extracted_dir' snake_case_ = tmp_path / 'custom_extracted_path' if default_extracted: snake_case_ = ('downloads' if default_cache_dir else custom_cache_dir, 'extracted') else: monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_DIR' , a_) monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(a_)) snake_case_ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) snake_case_ = xz_file snake_case_ = ( DownloadConfig(extract_compressed_file=a_) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=a_) ) snake_case_ = cached_path(a_ , download_config=a_) assert Path(a_).parent.parts[-2:] == expected def __UpperCAmelCase ( a_): # absolute path snake_case_ = str(Path(a_).resolve()) assert cached_path(a_) == text_file # relative path snake_case_ = str(Path(a_).resolve().relative_to(Path(os.getcwd()))) assert cached_path(a_) == text_file def __UpperCAmelCase ( a_): # absolute path snake_case_ = str(tmp_path.resolve() / '__missing_file__.txt') with pytest.raises(a_): cached_path(a_) # relative path snake_case_ = './__missing_file__.txt' with pytest.raises(a_): cached_path(a_) def __UpperCAmelCase ( a_): snake_case_ = get_from_cache(f'''tmp://{tmpfs_file}''') with open(a_) as f: snake_case_ = f.read() assert output_file_content == FILE_CONTENT @patch('datasets.config.HF_DATASETS_OFFLINE' , a_) def __UpperCAmelCase ( ): with pytest.raises(a_): cached_path('https://huggingface.co') @patch('datasets.config.HF_DATASETS_OFFLINE' , a_) def __UpperCAmelCase ( a_): snake_case_ = tmp_path_factory.mktemp('data') / 'file.html' with pytest.raises(a_): http_get('https://huggingface.co' , temp_file=a_) with pytest.raises(a_): http_head('https://huggingface.co') @patch('datasets.config.HF_DATASETS_OFFLINE' , a_) def __UpperCAmelCase ( a_): snake_case_ = tmp_path_factory.mktemp('data') / 'file.html' with pytest.raises(a_): ftp_get('ftp://huggingface.co' , temp_file=a_) with pytest.raises(a_): ftp_head('ftp://huggingface.co') @patch('datasets.config.HF_DATASETS_OFFLINE' , a_) def __UpperCAmelCase ( a_): snake_case_ = tmp_path_factory.mktemp('data') / 'file.html' with pytest.raises(a_): fsspec_get('s3://huggingface.co' , temp_file=a_) with pytest.raises(a_): fsspec_head('s3://huggingface.co')
178
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCAmelCase_ : Optional[Any] = {'''processing_wav2vec2_with_lm''': ['''Wav2Vec2ProcessorWithLM''']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys lowerCAmelCase_ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
248
"""simple docstring""" def _lowerCAmelCase ( ): '''simple docstring''' return [ a * b * (1000 - a - b) for a in range(1 , 999 ) for b in range(lowerCAmelCase , 999 ) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(F'{solution() = }')
248
1
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device __A = False class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" pass @nightly @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' ) # remove text_unet pipe.remove_unused_weights() pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = '''A painting of a squirrel eating a burger ''' lowerCAmelCase__ :str = torch.manual_seed(0 ) lowerCAmelCase__ :str = pipe( prompt=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = VersatileDiffusionTextToImagePipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[int] = generator.manual_seed(0 ) lowerCAmelCase__ :Union[str, Any] = pipe( prompt=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = VersatileDiffusionTextToImagePipeline.from_pretrained( 'shi-labs/versatile-diffusion' , torch_dtype=torch.floataa ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = '''A painting of a squirrel eating a burger ''' lowerCAmelCase__ :str = torch.manual_seed(0 ) lowerCAmelCase__ :Optional[int] = pipe( prompt=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='numpy' ).images lowerCAmelCase__ :Dict = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase__ :Optional[int] = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
293
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _lowerCamelCase ( UpperCamelCase , unittest.TestCase ): """simple docstring""" snake_case = DDIMPipeline snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS snake_case = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS snake_case = False def _snake_case ( self )->List[str]: '''simple docstring''' torch.manual_seed(0 ) A_ : List[str] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) A_ : Optional[Any] = DDIMScheduler() A_ : str = {'''unet''': unet, '''scheduler''': scheduler} return components def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 )->Optional[Any]: '''simple docstring''' if str(_SCREAMING_SNAKE_CASE ).startswith('''mps''' ): A_ : Any = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: A_ : Optional[int] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) A_ : Any = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def _snake_case ( self )->List[Any]: '''simple docstring''' A_ : Optional[int] = '''cpu''' A_ : Dict = self.get_dummy_components() A_ : str = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) A_ : str = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) A_ : Any = pipe(**_SCREAMING_SNAKE_CASE ).images A_ : int = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A_ : List[Any] = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A_ : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-3 ) def _snake_case ( self )->Union[str, Any]: '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def _snake_case ( self )->Optional[int]: '''simple docstring''' super().test_save_load_local(expected_max_difference=3e-3 ) def _snake_case ( self )->Optional[int]: '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=3e-3 ) def _snake_case ( self )->Any: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class _lowerCamelCase ( unittest.TestCase ): """simple docstring""" def _snake_case ( self )->Union[str, Any]: '''simple docstring''' A_ : int = '''google/ddpm-cifar10-32''' A_ : Tuple = UNetaDModel.from_pretrained(_SCREAMING_SNAKE_CASE ) A_ : str = DDIMScheduler() A_ : str = DDIMPipeline(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) ddim.to(_SCREAMING_SNAKE_CASE ) ddim.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = torch.manual_seed(0 ) A_ : Any = ddim(generator=_SCREAMING_SNAKE_CASE , eta=0.0 , output_type='''numpy''' ).images A_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A_ : Any = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _snake_case ( self )->List[str]: '''simple docstring''' A_ : Tuple = '''google/ddpm-ema-bedroom-256''' A_ : int = UNetaDModel.from_pretrained(_SCREAMING_SNAKE_CASE ) A_ : Any = DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = DDIMPipeline(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) ddpm.to(_SCREAMING_SNAKE_CASE ) ddpm.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) A_ : Dict = torch.manual_seed(0 ) A_ : List[str] = ddpm(generator=_SCREAMING_SNAKE_CASE , output_type='''numpy''' ).images A_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) A_ : Tuple = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
186
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A: Optional[Any] = logging.get_logger(__name__) A: List[str] = { "google/pegasus-large": "https://huggingface.co/google/pegasus-large/resolve/main/config.json", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class SCREAMING_SNAKE_CASE__ ( snake_case__ ): __lowerCAmelCase : int = 'pegasus' __lowerCAmelCase : Any = ['past_key_values'] __lowerCAmelCase : Any = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , _SCREAMING_SNAKE_CASE=50265 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , **_SCREAMING_SNAKE_CASE , ) -> Any: '''simple docstring''' UpperCAmelCase : Dict = vocab_size UpperCAmelCase : Dict = max_position_embeddings UpperCAmelCase : Optional[Any] = d_model UpperCAmelCase : List[Any] = encoder_ffn_dim UpperCAmelCase : List[str] = encoder_layers UpperCAmelCase : Optional[int] = encoder_attention_heads UpperCAmelCase : List[Any] = decoder_ffn_dim UpperCAmelCase : str = decoder_layers UpperCAmelCase : str = decoder_attention_heads UpperCAmelCase : List[Any] = dropout UpperCAmelCase : Optional[Any] = attention_dropout UpperCAmelCase : Optional[Any] = activation_dropout UpperCAmelCase : List[str] = activation_function UpperCAmelCase : Tuple = init_std UpperCAmelCase : Any = encoder_layerdrop UpperCAmelCase : int = decoder_layerdrop UpperCAmelCase : Optional[Any] = use_cache UpperCAmelCase : Optional[Any] = encoder_layers UpperCAmelCase : Dict = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , forced_eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' return self.d_model
365
"""simple docstring""" import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _snake_case ( UpperCamelCase : np.ndarray ): return input_array.reshape((input_array.size, 1) ) def _snake_case ( UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray , UpperCamelCase : int ): UpperCAmelCase : Optional[int] = np.nan for i in range(UpperCamelCase ): UpperCAmelCase : int = features[:, labels == i] UpperCAmelCase : List[Any] = data.mean(1 ) # Centralize the data of class i UpperCAmelCase : Dict = data - column_reshape(UpperCamelCase ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCamelCase , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) UpperCAmelCase : Optional[Any] = np.dot(UpperCamelCase , centered_data.T ) return covariance_sum / features.shape[1] def _snake_case ( UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray , UpperCamelCase : int ): UpperCAmelCase : Tuple = features.mean(1 ) UpperCAmelCase : Union[str, Any] = np.nan for i in range(UpperCamelCase ): UpperCAmelCase : int = features[:, labels == i] UpperCAmelCase : List[str] = data.shape[1] UpperCAmelCase : Optional[int] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCamelCase ) - column_reshape(UpperCamelCase ) , (column_reshape(UpperCamelCase ) - column_reshape(UpperCamelCase )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) UpperCAmelCase : Optional[Any] = device_data * np.dot( column_reshape(UpperCamelCase ) - column_reshape(UpperCamelCase ) , (column_reshape(UpperCamelCase ) - column_reshape(UpperCamelCase )).T , ) return covariance_sum / features.shape[1] def _snake_case ( UpperCamelCase : np.ndarray , UpperCamelCase : int ): # Check if the features have been loaded if features.any(): UpperCAmelCase : Tuple = features.mean(1 ) # Center the dataset UpperCAmelCase : List[str] = features - np.reshape(UpperCamelCase , (data_mean.size, 1) ) UpperCAmelCase : str = np.dot(UpperCamelCase , centered_data.T ) / features.shape[1] UpperCAmelCase , UpperCAmelCase : int = np.linalg.eigh(UpperCamelCase ) # Take all the columns in the reverse order (-1), and then takes only the first UpperCAmelCase : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space UpperCAmelCase : int = np.dot(filtered_eigenvectors.T , UpperCamelCase ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=UpperCamelCase ) logging.error("""Dataset empty""" ) raise AssertionError def _snake_case ( UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray , UpperCamelCase : int , UpperCamelCase : int ): assert classes > dimensions # Check if features have been already loaded if features.any: UpperCAmelCase , UpperCAmelCase : Dict = eigh( covariance_between_classes(UpperCamelCase , UpperCamelCase , UpperCamelCase ) , covariance_within_classes(UpperCamelCase , UpperCamelCase , UpperCamelCase ) , ) UpperCAmelCase : Any = eigenvectors[:, ::-1][:, :dimensions] UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Tuple = np.linalg.svd(UpperCamelCase ) UpperCAmelCase : Tuple = svd_matrix[:, 0:dimensions] UpperCAmelCase : Tuple = np.dot(filtered_svd_matrix.T , UpperCamelCase ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=UpperCamelCase ) logging.error("""Dataset empty""" ) raise AssertionError def _snake_case ( ): # Create dummy dataset with 2 classes and 3 features UpperCAmelCase : Dict = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) UpperCAmelCase : List[Any] = np.array([0, 0, 0, 1, 1] ) UpperCAmelCase : List[str] = 2 UpperCAmelCase : int = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCamelCase ) as error_info: UpperCAmelCase : Union[str, Any] = linear_discriminant_analysis( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) if isinstance(UpperCamelCase , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def _snake_case ( ): UpperCAmelCase : List[Any] = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) UpperCAmelCase : Optional[int] = 2 UpperCAmelCase : Any = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCamelCase ) as error_info: UpperCAmelCase : Tuple = principal_component_analysis(UpperCamelCase , UpperCamelCase ) if not np.allclose(UpperCamelCase , UpperCamelCase ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
76
0
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def UpperCamelCase_( lowerCamelCase_="" ) -> str: _lowercase : Optional[Any] = tempfile.mkdtemp() return os.path.join(lowerCamelCase_ , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : List[Any] = torch.rand(12, dtype=torch.floataa) - 0.5 _lowercase : Dict = AgentAudio(lowerCamelCase) _lowercase : List[Any] = str(agent_type.to_string()) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(lowerCamelCase, agent_type.to_raw(), atol=1E-4)) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(lowerCamelCase)) # Ensure that the file contains the same value as the original tensor _lowercase , _lowercase : List[Any] = sf.read(lowerCamelCase) self.assertTrue(torch.allclose(lowerCamelCase, torch.tensor(lowerCamelCase), atol=1E-4)) def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : List[str] = torch.rand(12, dtype=torch.floataa) - 0.5 _lowercase : Optional[Any] = get_new_path(suffix='.wav') sf.write(lowerCamelCase, lowerCamelCase, 1_60_00) _lowercase : List[str] = AgentAudio(lowerCamelCase) self.assertTrue(torch.allclose(lowerCamelCase, agent_type.to_raw(), atol=1E-4)) self.assertEqual(agent_type.to_string(), lowerCamelCase) @require_vision @require_torch class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : str = torch.randint(0, 2_56, (64, 64, 3)) _lowercase : List[Any] = AgentImage(lowerCamelCase) _lowercase : Any = str(agent_type.to_string()) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(lowerCamelCase, agent_type._tensor, atol=1E-4)) self.assertIsInstance(agent_type.to_raw(), Image.Image) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase)) def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : Optional[Any] = Path(get_tests_dir('fixtures/tests_samples/COCO')) / '000000039769.png' _lowercase : Any = Image.open(lowerCamelCase) _lowercase : Optional[int] = AgentImage(lowerCamelCase) self.assertTrue(path.samefile(agent_type.to_string())) self.assertTrue(image == agent_type.to_raw()) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase)) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Optional[int] = Path(get_tests_dir('fixtures/tests_samples/COCO')) / '000000039769.png' _lowercase : Optional[int] = Image.open(lowerCamelCase) _lowercase : List[str] = AgentImage(lowerCamelCase) self.assertFalse(path.samefile(agent_type.to_string())) self.assertTrue(image == agent_type.to_raw()) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase)) class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Optional[int] = 'Hey!' _lowercase : List[str] = AgentText(lowerCamelCase) self.assertEqual(lowerCamelCase, agent_type.to_string()) self.assertEqual(lowerCamelCase, agent_type.to_raw()) self.assertEqual(lowerCamelCase, lowerCamelCase)
21
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def UpperCamelCase_( lowerCamelCase_ ) -> Optional[int]: if isinstance(lowerCamelCase_ , collections.abc.Iterable ): return x return (x, x) @require_flax class _lowerCamelCase: def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Union[str, Any]: """simple docstring""" pass def UpperCamelCase ( self) -> str: """simple docstring""" pass def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" pass def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Any: """simple docstring""" _lowercase : str = np.abs((a - b)).max() self.assertLessEqual(lowerCamelCase, lowerCamelCase, F'''Difference between torch and flax is {diff} (>= {tol}).''') def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase) -> Union[str, Any]: """simple docstring""" _lowercase : Any = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase, lowerCamelCase) _lowercase : Optional[int] = FlaxVisionTextDualEncoderModel(lowerCamelCase) _lowercase : Any = model(input_ids=lowerCamelCase, pixel_values=lowerCamelCase, attention_mask=lowerCamelCase) self.assertEqual(output['text_embeds'].shape, (input_ids.shape[0], config.projection_dim)) self.assertEqual(output['image_embeds'].shape, (pixel_values.shape[0], config.projection_dim)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase) -> Any: """simple docstring""" _lowercase , _lowercase : Union[str, Any] = self.get_vision_text_model(lowerCamelCase, lowerCamelCase) _lowercase : str = {'vision_model': vision_model, 'text_model': text_model} _lowercase : Dict = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase) _lowercase : List[str] = model(input_ids=lowerCamelCase, pixel_values=lowerCamelCase, attention_mask=lowerCamelCase) self.assertEqual(output['text_embeds'].shape, (input_ids.shape[0], model.config.projection_dim)) self.assertEqual(output['image_embeds'].shape, (pixel_values.shape[0], model.config.projection_dim)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase) -> Union[str, Any]: """simple docstring""" _lowercase , _lowercase : Tuple = self.get_vision_text_model(lowerCamelCase, lowerCamelCase) _lowercase : List[str] = {'vision_model': vision_model, 'text_model': text_model} _lowercase : Dict = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase) _lowercase : List[str] = model(input_ids=lowerCamelCase, pixel_values=lowerCamelCase, attention_mask=lowerCamelCase) _lowercase : Tuple = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowerCamelCase) _lowercase : Any = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase) _lowercase : Tuple = model(input_ids=lowerCamelCase, pixel_values=lowerCamelCase, attention_mask=lowerCamelCase) _lowercase : str = after_output[0] _lowercase : Optional[Any] = np.amax(np.abs(out_a - out_a)) self.assertLessEqual(lowerCamelCase, 1E-3) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase) -> str: """simple docstring""" _lowercase , _lowercase : Any = self.get_vision_text_model(lowerCamelCase, lowerCamelCase) _lowercase : Optional[int] = {'vision_model': vision_model, 'text_model': text_model} _lowercase : Dict = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase) _lowercase : Tuple = model( input_ids=lowerCamelCase, pixel_values=lowerCamelCase, attention_mask=lowerCamelCase, output_attentions=lowerCamelCase) _lowercase : int = output.vision_model_output.attentions self.assertEqual(len(lowerCamelCase), vision_config.num_hidden_layers) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) _lowercase : Optional[Any] = to_atuple(vision_model.config.image_size) _lowercase : Any = to_atuple(vision_model.config.patch_size) _lowercase : Dict = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) _lowercase : Dict = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:], (vision_config.num_attention_heads, seq_len, seq_len)) _lowercase : List[str] = output.text_model_output.attentions self.assertEqual(len(lowerCamelCase), text_config.num_hidden_layers) self.assertEqual( text_attentions[0].shape[-3:], (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]), ) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Optional[int]: """simple docstring""" pt_model.to(lowerCamelCase) pt_model.eval() # prepare inputs _lowercase : Any = inputs_dict _lowercase : Optional[int] = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} with torch.no_grad(): _lowercase : Tuple = pt_model(**lowerCamelCase).to_tuple() _lowercase : Any = fx_model(**lowerCamelCase).to_tuple() self.assertEqual(len(lowerCamelCase), len(lowerCamelCase), 'Output lengths differ between Flax and PyTorch') for fx_output, pt_output in zip(fx_outputs[:4], pt_outputs[:4]): self.assert_almost_equals(lowerCamelCase, pt_output.numpy(), 4E-2) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(lowerCamelCase) _lowercase : int = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase, from_pt=lowerCamelCase) _lowercase : List[Any] = fx_model_loaded(**lowerCamelCase).to_tuple() self.assertEqual(len(lowerCamelCase), len(lowerCamelCase), 'Output lengths differ between Flax and PyTorch') for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4], pt_outputs[:4]): self.assert_almost_equals(lowerCamelCase, pt_output.numpy(), 4E-2) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(lowerCamelCase) _lowercase : List[Any] = VisionTextDualEncoderModel.from_pretrained(lowerCamelCase, from_flax=lowerCamelCase) pt_model_loaded.to(lowerCamelCase) pt_model_loaded.eval() with torch.no_grad(): _lowercase : Optional[Any] = pt_model_loaded(**lowerCamelCase).to_tuple() self.assertEqual(len(lowerCamelCase), len(lowerCamelCase), 'Output lengths differ between Flax and PyTorch') for fx_output, pt_output_loaded in zip(fx_outputs[:4], pt_outputs_loaded[:4]): self.assert_almost_equals(lowerCamelCase, pt_output_loaded.numpy(), 4E-2) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Tuple: """simple docstring""" _lowercase : Dict = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase, lowerCamelCase) _lowercase : Optional[Any] = VisionTextDualEncoderModel(lowerCamelCase) _lowercase : str = FlaxVisionTextDualEncoderModel(lowerCamelCase) _lowercase : Tuple = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), lowerCamelCase) _lowercase : List[Any] = fx_state self.check_pt_flax_equivalence(lowerCamelCase, lowerCamelCase, lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Dict: """simple docstring""" _lowercase : str = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase, lowerCamelCase) _lowercase : Tuple = VisionTextDualEncoderModel(lowerCamelCase) _lowercase : Optional[int] = FlaxVisionTextDualEncoderModel(lowerCamelCase) _lowercase : List[str] = load_flax_weights_in_pytorch_model(lowerCamelCase, fx_model.params) self.check_pt_flax_equivalence(lowerCamelCase, lowerCamelCase, lowerCamelCase) def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : int = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowerCamelCase) def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : List[str] = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase) def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : Optional[int] = self.prepare_config_and_inputs() self.check_save_load(**lowerCamelCase) def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : str = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowerCamelCase) @is_pt_flax_cross_test def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : List[Any] = self.prepare_config_and_inputs() _lowercase : List[str] = config_inputs_dict.pop('vision_config') _lowercase : str = config_inputs_dict.pop('text_config') _lowercase : int = config_inputs_dict self.check_equivalence_pt_to_flax(lowerCamelCase, lowerCamelCase, lowerCamelCase) self.check_equivalence_flax_to_pt(lowerCamelCase, lowerCamelCase, lowerCamelCase) @slow def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase , _lowercase : Optional[Any] = self.get_pretrained_model_and_inputs() _lowercase : Optional[int] = model_a(**lowerCamelCase) _lowercase : Tuple = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowerCamelCase) _lowercase : int = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase) _lowercase : List[Any] = model_a(**lowerCamelCase) _lowercase : Tuple = after_outputs[0] _lowercase : Dict = np.amax(np.abs(out_a - out_a)) self.assertLessEqual(lowerCamelCase, 1E-5) @require_flax class _lowerCamelCase( _a, unittest.TestCase ): def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit', 'hf-internal-testing/tiny-bert', vision_from_pt=lowerCamelCase, text_from_pt=lowerCamelCase, ) _lowercase : List[Any] = 13 _lowercase : str = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ]) _lowercase : Tuple = ids_tensor([batch_size, 4], model.config.text_config.vocab_size) _lowercase : Union[str, Any] = random_attention_mask([batch_size, 4]) _lowercase : int = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Any: """simple docstring""" _lowercase : List[Any] = FlaxViTModel(lowerCamelCase) _lowercase : Optional[Any] = FlaxBertModel(lowerCamelCase) return vision_model, text_model def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : List[Any] = FlaxViTModelTester(self) _lowercase : Any = FlaxBertModelTester(self) _lowercase : Dict = vit_model_tester.prepare_config_and_inputs() _lowercase : Any = bert_model_tester.prepare_config_and_inputs() _lowercase , _lowercase : List[str] = vision_config_and_inputs _lowercase , _lowercase , _lowercase , _lowercase : Tuple = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class _lowerCamelCase( _a, unittest.TestCase ): def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-clip', 'hf-internal-testing/tiny-bert', vision_from_pt=lowerCamelCase, text_from_pt=lowerCamelCase, ) _lowercase : Tuple = 13 _lowercase : Any = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ]) _lowercase : Union[str, Any] = ids_tensor([batch_size, 4], model.config.text_config.vocab_size) _lowercase : Any = random_attention_mask([batch_size, 4]) _lowercase : Dict = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Optional[int]: """simple docstring""" _lowercase : Any = FlaxCLIPVisionModel(lowerCamelCase) _lowercase : Optional[Any] = FlaxBertModel(lowerCamelCase) return vision_model, text_model def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : Tuple = FlaxCLIPVisionModelTester(self) _lowercase : Union[str, Any] = FlaxBertModelTester(self) _lowercase : Tuple = clip_model_tester.prepare_config_and_inputs() _lowercase : str = bert_model_tester.prepare_config_and_inputs() _lowercase , _lowercase : Dict = vision_config_and_inputs _lowercase , _lowercase , _lowercase , _lowercase : Optional[int] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class _lowerCamelCase( unittest.TestCase ): @slow def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : List[str] = FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian', logit_scale_init_value=1.0) _lowercase : List[str] = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian') _lowercase : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') _lowercase : List[Any] = processor( text=['una foto di un gatto', 'una foto di un cane'], images=lowerCamelCase, padding=lowerCamelCase, return_tensors='np') _lowercase : List[Any] = model(**lowerCamelCase) # verify the logits self.assertEqual(outputs.logits_per_image.shape, (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])) self.assertEqual( outputs.logits_per_text.shape, (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]), ) _lowercase : Optional[int] = np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]) self.assertTrue(np.allclose(outputs.logits_per_image, lowerCamelCase, atol=1E-3))
21
1
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch __snake_case : Optional[Any] = logging.get_logger(__name__) class __UpperCAmelCase ( _lowerCAmelCase ): __lowercase : str = ['pixel_values'] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE_ ) A_ = size if size is not None else {"""shortest_edge""": 256} A_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) A_ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} A_ = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) A_ = do_resize A_ = size A_ = resample A_ = do_center_crop A_ = crop_size A_ = do_rescale A_ = rescale_factor A_ = do_normalize A_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: A_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "shortest_edge" not in size: raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) A_ = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=size['''shortest_edge'''] , default_to_square=SCREAMING_SNAKE_CASE_ ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: A_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}''' ) return center_crop(SCREAMING_SNAKE_CASE_ , size=(size['''height'''], size['''width''']) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , ) -> Any: A_ = do_resize if do_resize is not None else self.do_resize A_ = size if size is not None else self.size A_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) A_ = resample if resample is not None else self.resample A_ = do_center_crop if do_center_crop is not None else self.do_center_crop A_ = crop_size if crop_size is not None else self.crop_size A_ = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) A_ = do_rescale if do_rescale is not None else self.do_rescale A_ = rescale_factor if rescale_factor is not None else self.rescale_factor A_ = do_normalize if do_normalize is not None else self.do_normalize A_ = image_mean if image_mean is not None else self.image_mean A_ = image_std if image_std is not None else self.image_std A_ = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. A_ = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: A_ = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: A_ = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: A_ = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: A_ = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] A_ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] A_ = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple: A_ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): A_ = target_sizes.numpy() A_ = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): A_ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=SCREAMING_SNAKE_CASE_ ) A_ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: A_ = logits.argmax(dim=1 ) A_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
365
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case : List[str] = logging.get_logger(__name__) __snake_case : Union[str, Any] = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class __UpperCAmelCase ( _UpperCamelCase ): '''simple docstring''' __lowercase : Optional[int] = 'mgp-str' def __init__( self , _SCREAMING_SNAKE_CASE=[32, 128] , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=27 , _SCREAMING_SNAKE_CASE=38 , _SCREAMING_SNAKE_CASE=5_0257 , _SCREAMING_SNAKE_CASE=3_0522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0.02 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: super().__init__(**_SCREAMING_SNAKE_CASE ) A_ = image_size A_ = patch_size A_ = num_channels A_ = max_token_length A_ = num_character_labels A_ = num_bpe_labels A_ = num_wordpiece_labels A_ = hidden_size A_ = num_hidden_layers A_ = num_attention_heads A_ = mlp_ratio A_ = distilled A_ = layer_norm_eps A_ = drop_rate A_ = qkv_bias A_ = attn_drop_rate A_ = drop_path_rate A_ = output_aa_attentions A_ = initializer_range
18
0
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline __snake_case :List[Any] = logging.get_logger(__name__) @add_end_docstrings(__UpperCAmelCase ) class _A ( __UpperCAmelCase ): def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE) if self.framework != "pt": raise ValueError(F'The {self.__class__} is only available in PyTorch.') # No specific FOR_XXX available yet def __call__( self : Tuple , __SCREAMING_SNAKE_CASE : Union[np.ndarray, bytes, str] , **__SCREAMING_SNAKE_CASE : int): '''simple docstring''' return super().__call__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def _lowerCamelCase ( self : List[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Tuple="This is a sound of {}."): '''simple docstring''' if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): if audio.startswith('''http://''') or audio.startswith('''https://'''): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__SCREAMING_SNAKE_CASE).content else: with open(__SCREAMING_SNAKE_CASE , '''rb''') as f: __a = f.read() if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): __a = ffmpeg_read(__SCREAMING_SNAKE_CASE , self.feature_extractor.sampling_rate) if not isinstance(__SCREAMING_SNAKE_CASE , np.ndarray): raise ValueError('''We expect a numpy ndarray as input''') if len(audio.shape) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''') __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''') __a = candidate_labels __a = [hypothesis_template.format(__SCREAMING_SNAKE_CASE) for x in candidate_labels] __a = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=__SCREAMING_SNAKE_CASE) __a = [text_inputs] return inputs def _lowerCamelCase ( self : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' __a = model_inputs.pop('''candidate_labels''') __a = model_inputs.pop('''text_inputs''') if isinstance(text_inputs[0] , __SCREAMING_SNAKE_CASE): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def _lowerCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' __a = model_outputs.pop('''candidate_labels''') __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''') __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) , key=lambda __SCREAMING_SNAKE_CASE: -x[0]) ] return result
49
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def __snake_case ( _UpperCAmelCase = "isbn/0140328726" ): __a = olid.strip().strip('''/''' ) # Remove leading/trailing whitespace & slashes if new_olid.count('''/''' ) != 1: __a = f'{olid} is not a valid Open Library olid' raise ValueError(_UpperCAmelCase ) return requests.get(f'https://openlibrary.org/{new_olid}.json' ).json() def __snake_case ( _UpperCAmelCase ): __a = { '''title''': '''Title''', '''publish_date''': '''Publish date''', '''authors''': '''Authors''', '''number_of_pages''': '''Number of pages:''', '''first_sentence''': '''First sentence''', '''isbn_10''': '''ISBN (10)''', '''isbn_13''': '''ISBN (13)''', } __a = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __a = [ get_openlibrary_data(author['''key'''] )['''name'''] for author in data['''Authors'''] ] __a = data['''First sentence''']['''value'''] for key, value in data.items(): if isinstance(_UpperCAmelCase , _UpperCAmelCase ): __a = ''', '''.join(_UpperCAmelCase ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: __snake_case :List[Any] = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.') continue print(f'\nSearching Open Library for ISBN: {isbn}...\n') try: __snake_case :Optional[Any] = summarize_book(get_openlibrary_data(f'isbn/{isbn}')) print('''\n'''.join(f'{key}: {value}' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'Sorry, there are no results for ISBN: {isbn}.')
49
1
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : int , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] ): """simple docstring""" UpperCamelCase = dataset UpperCamelCase = process UpperCamelCase = params def __len__( self : List[str] ): """simple docstring""" return len(self.dataset ) def __getitem__( self : List[Any] , UpperCamelCase__ : List[str] ): """simple docstring""" UpperCamelCase = self.dataset[i] UpperCamelCase = self.process(UpperCamelCase__ , **self.params ) return processed class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str=None ): """simple docstring""" UpperCamelCase = loader UpperCamelCase = infer UpperCamelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether UpperCamelCase = None UpperCamelCase = loader_batch_size # Internal bookkeeping UpperCamelCase = None UpperCamelCase = None def __len__( self : Optional[int] ): """simple docstring""" return len(self.loader ) def __iter__( self : Any ): """simple docstring""" UpperCamelCase = iter(self.loader ) return self def A ( self : Dict ): """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice UpperCamelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) UpperCamelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first UpperCamelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around UpperCamelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCamelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCamelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. UpperCamelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 UpperCamelCase = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def A ( self : Optional[Any] ): """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch UpperCamelCase = next(self.iterator ) UpperCamelCase = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): UpperCamelCase = processed else: UpperCamelCase = list(processed.keys() )[0] UpperCamelCase = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase = len(UpperCamelCase__ ) else: UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCamelCase = observed_batch_size # Setting internal index to unwrap the batch UpperCamelCase = processed UpperCamelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : int=None ): """simple docstring""" super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self : Optional[Any] ): """simple docstring""" UpperCamelCase = iter(self.loader ) UpperCamelCase = None return self def A ( self : Optional[Any] ): """simple docstring""" if self.subiterator is None: UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item UpperCamelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) UpperCamelCase = next(self.subiterator ) return processed class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __iter__( self : Dict ): """simple docstring""" UpperCamelCase = iter(self.loader ) return self def A ( self : Tuple ): """simple docstring""" UpperCamelCase = False UpperCamelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: UpperCamelCase = self.loader_batch_item() UpperCamelCase = item.pop('is_last' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): UpperCamelCase = processed else: UpperCamelCase = list(processed.keys() )[0] UpperCamelCase = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase = len(UpperCamelCase__ ) else: UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCamelCase = observed_batch_size UpperCamelCase = processed UpperCamelCase = 0 while self._loader_batch_index < self.loader_batch_size: UpperCamelCase = self.loader_batch_item() UpperCamelCase = item.pop('is_last' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: UpperCamelCase = processed UpperCamelCase = item.pop('is_last' ) accumulator.append(UpperCamelCase__ ) return accumulator class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : Any , UpperCamelCase__ : Dataset , UpperCamelCase__ : str ): """simple docstring""" UpperCamelCase = dataset UpperCamelCase = key def __len__( self : Tuple ): """simple docstring""" return len(self.dataset ) def __getitem__( self : List[Any] , UpperCamelCase__ : str ): """simple docstring""" return self.dataset[i][self.key] class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : List[str] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str , UpperCamelCase__ : str ): """simple docstring""" UpperCamelCase = dataset UpperCamelCase = keya UpperCamelCase = keya def __len__( self : int ): """simple docstring""" return len(self.dataset ) def __getitem__( self : Optional[Any] , UpperCamelCase__ : str ): """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
249
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __lowerCamelCase ( A__ ) -> Any: """simple docstring""" UpperCamelCase , UpperCamelCase = image.size UpperCamelCase , UpperCamelCase = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase = image.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) UpperCamelCase = np.array(A__ ).astype(np.floataa ) / 255.0 UpperCamelCase = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase = torch.from_numpy(A__ ) return 2.0 * image - 1.0 class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : str , UpperCamelCase__ : VQModel , UpperCamelCase__ : UNetaDModel , UpperCamelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCamelCase__ , unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) @torch.no_grad() def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , UpperCamelCase__ : Optional[int] = 1 , UpperCamelCase__ : Optional[int] = 1_0_0 , UpperCamelCase__ : Optional[float] = 0.0 , UpperCamelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase__ : Optional[str] = "pil" , UpperCamelCase__ : bool = True , ): """simple docstring""" if isinstance(UpperCamelCase__ , PIL.Image.Image ): UpperCamelCase = 1 elif isinstance(UpperCamelCase__ , torch.Tensor ): UpperCamelCase = image.shape[0] else: raise ValueError(f"""`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(UpperCamelCase__ )}""" ) if isinstance(UpperCamelCase__ , PIL.Image.Image ): UpperCamelCase = preprocess(UpperCamelCase__ ) UpperCamelCase , UpperCamelCase = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase = next(self.unet.parameters() ).dtype UpperCamelCase = randn_tensor(UpperCamelCase__ , generator=UpperCamelCase__ , device=self.device , dtype=UpperCamelCase__ ) UpperCamelCase = image.to(device=self.device , dtype=UpperCamelCase__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(UpperCamelCase__ , device=self.device ) UpperCamelCase = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase = {} if accepts_eta: UpperCamelCase = eta for t in self.progress_bar(UpperCamelCase__ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase = torch.cat([latents, image] , dim=1 ) UpperCamelCase = self.scheduler.scale_model_input(UpperCamelCase__ , UpperCamelCase__ ) # predict the noise residual UpperCamelCase = self.unet(UpperCamelCase__ , UpperCamelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase = self.scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase = self.vqvae.decode(UpperCamelCase__ ).sample UpperCamelCase = torch.clamp(UpperCamelCase__ , -1.0 , 1.0 ) UpperCamelCase = image / 2 + 0.5 UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase = self.numpy_to_pil(UpperCamelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCamelCase__ )
249
1
def _lowerCAmelCase (_lowerCAmelCase): if not numbers: return 0 if not isinstance(_lowerCAmelCase , (list, tuple)) or not all( isinstance(_lowerCAmelCase , _lowerCAmelCase) for number in numbers): raise ValueError("numbers must be an iterable of integers") UpperCamelCase_ = UpperCamelCase_ = UpperCamelCase_ = numbers[0] for i in range(1 , len(_lowerCAmelCase)): # update the maximum and minimum subarray products UpperCamelCase_ = numbers[i] if number < 0: UpperCamelCase_ , UpperCamelCase_ = min_till_now, max_till_now UpperCamelCase_ = max(_lowerCAmelCase , max_till_now * number) UpperCamelCase_ = min(_lowerCAmelCase , min_till_now * number) # update the maximum product found till now UpperCamelCase_ = max(_lowerCAmelCase , _lowerCAmelCase) return max_prod
128
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) UpperCAmelCase : Tuple =2_9979_2458 # Symbols UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : int =symbols("""ct x y z""") def _lowerCAmelCase (_lowerCAmelCase): if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!") elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!") return velocity / c def _lowerCAmelCase (_lowerCAmelCase): return 1 / sqrt(1 - beta(_lowerCAmelCase) ** 2) def _lowerCAmelCase (_lowerCAmelCase): return np.array( [ [gamma(_lowerCAmelCase), -gamma(_lowerCAmelCase) * beta(_lowerCAmelCase), 0, 0], [-gamma(_lowerCAmelCase) * beta(_lowerCAmelCase), gamma(_lowerCAmelCase), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ]) def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase = None): # Ensure event is not empty if event is None: UpperCamelCase_ = np.array([ct, x, y, z]) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(_lowerCAmelCase) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: UpperCAmelCase : Optional[Any] =transform(2997_9245) print("""Example of four vector: """) print(F"ct' = {four_vector[0]}") print(F"x' = {four_vector[1]}") print(F"y' = {four_vector[2]}") print(F"z' = {four_vector[3]}") # Substitute symbols with numerical values UpperCAmelCase : List[Any] ={ct: c, x: 1, y: 1, z: 1} UpperCAmelCase : Optional[Any] =[four_vector[i].subs(sub_dict) for i in range(4)] print(F"\n{numerical_vector}")
128
1
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCamelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ = 1_60_00 ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE = int(round(sample_rate * max_length ) ) if len(snake_case__ ) <= sample_length: return wav _SCREAMING_SNAKE_CASE = randint(0 ,len(snake_case__ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class __UpperCAmelCase : __snake_case : Optional[str] = field(default=_UpperCAmelCase ,metadata={"help": "Name of a dataset from the datasets package"} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "A file containing the training audio paths and labels."} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "A file containing the validation audio paths and labels."} ) __snake_case : str = field( default="train" ,metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } ,) __snake_case : str = field( default="validation" ,metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } ,) __snake_case : str = field( default="audio" ,metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} ,) __snake_case : str = field( default="label" ,metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) __snake_case : Optional[int] = field( default=_UpperCAmelCase ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } ,) __snake_case : Optional[int] = field( default=_UpperCAmelCase ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } ,) __snake_case : float = field( default=20 ,metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} ,) @dataclass class __UpperCAmelCase : __snake_case : str = field( default="facebook/wav2vec2-base" ,metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ,) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) __snake_case : str = field( default="main" ,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} ,) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Name or path of preprocessor config."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } ,) __snake_case : Optional[bool] = field( default=_UpperCAmelCase ,metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} ,) def UpperCamelCase ( self: List[str] ): '''simple docstring''' if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( """The argument `--freeze_feature_extractor` is deprecated and """ """will be removed in a future version. Use `--freeze_feature_encoder`""" """instead. Setting `freeze_feature_encoder==True`.""" , UpperCAmelCase_ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( """The argument `--freeze_feature_extractor` is deprecated and """ """should not be used in combination with `--freeze_feature_encoder`.""" """Only make use of `--freeze_feature_encoder`.""" ) def __lowerCamelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_audio_classification""" ,snake_case__ ,snake_case__ ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(snake_case__ ) transformers.utils.logging.set_verbosity(snake_case__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} ' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to train from scratch.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset and prepare it for the audio classification task. _SCREAMING_SNAKE_CASE = DatasetDict() _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.train_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.eval_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ' """Make sure to set `--audio_column_name` to the correct audio column - one of """ F'{", ".join(raw_datasets["train"].column_names )}.' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ' """Make sure to set `--label_column_name` to the correct text column - one of """ F'{", ".join(raw_datasets["train"].column_names )}.' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy _SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path ,return_attention_mask=model_args.attention_mask ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. _SCREAMING_SNAKE_CASE = raw_datasets.cast_column( data_args.audio_column_name ,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) _SCREAMING_SNAKE_CASE = feature_extractor.model_input_names[0] def train_transforms(snake_case__ ): _SCREAMING_SNAKE_CASE = [] for audio in batch[data_args.audio_column_name]: _SCREAMING_SNAKE_CASE = random_subsample( audio["""array"""] ,max_length=data_args.max_length_seconds ,sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(snake_case__ ) _SCREAMING_SNAKE_CASE = feature_extractor(snake_case__ ,sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(snake_case__ )} _SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(snake_case__ ): _SCREAMING_SNAKE_CASE = [audio["""array"""] for audio in batch[data_args.audio_column_name]] _SCREAMING_SNAKE_CASE = feature_extractor(snake_case__ ,sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(snake_case__ )} _SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _SCREAMING_SNAKE_CASE = raw_datasets["""train"""].features[data_args.label_column_name].names _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = {}, {} for i, label in enumerate(snake_case__ ): _SCREAMING_SNAKE_CASE = str(snake_case__ ) _SCREAMING_SNAKE_CASE = label # Load the accuracy metric from the datasets package _SCREAMING_SNAKE_CASE = evaluate.load("""accuracy""" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(snake_case__ ): _SCREAMING_SNAKE_CASE = np.argmax(eval_pred.predictions ,axis=1 ) return metric.compute(predictions=snake_case__ ,references=eval_pred.label_ids ) _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path ,num_labels=len(snake_case__ ) ,labelaid=snake_case__ ,idalabel=snake_case__ ,finetuning_task="""audio-classification""" ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) _SCREAMING_SNAKE_CASE = AutoModelForAudioClassification.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 ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE = ( raw_datasets["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(snake_case__ ,output_all_columns=snake_case__ ) if training_args.do_eval: if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE = ( raw_datasets["""eval"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(snake_case__ ,output_all_columns=snake_case__ ) # Initialize our trainer _SCREAMING_SNAKE_CASE = Trainer( model=snake_case__ ,args=snake_case__ ,train_dataset=raw_datasets["""train"""] if training_args.do_train else None ,eval_dataset=raw_datasets["""eval"""] if training_args.do_eval else None ,compute_metrics=snake_case__ ,tokenizer=snake_case__ ,) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE = last_checkpoint _SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=snake_case__ ) trainer.save_model() trainer.log_metrics("""train""" ,train_result.metrics ) trainer.save_metrics("""train""" ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE = trainer.evaluate() trainer.log_metrics("""eval""" ,snake_case__ ) trainer.save_metrics("""eval""" ,snake_case__ ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE = { """finetuned_from""": model_args.model_name_or_path, """tasks""": """audio-classification""", """dataset""": data_args.dataset_name, """tags""": ["""audio-classification"""], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case__ ) else: trainer.create_model_card(**snake_case__ ) if __name__ == "__main__": main()
365
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'encoder.deit.blocks.{i}.norm1.weight', F'encoder.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'encoder.deit.blocks.{i}.norm1.bias', F'encoder.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.attn.proj.weight', F'encoder.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (F'encoder.deit.blocks.{i}.attn.proj.bias', F'encoder.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.norm2.weight', F'encoder.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'encoder.deit.blocks.{i}.norm2.bias', F'encoder.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.mlp.fc1.weight', F'encoder.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append( (F'encoder.deit.blocks.{i}.mlp.fc1.bias', F'encoder.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.mlp.fc2.weight', F'encoder.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'encoder.deit.blocks.{i}.mlp.fc2.bias', F'encoder.encoder.layer.{i}.output.dense.bias') ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ("""encoder.deit.cls_token""", """encoder.embeddings.cls_token"""), ("""encoder.deit.pos_embed""", """encoder.embeddings.position_embeddings"""), ("""encoder.deit.patch_embed.proj.weight""", """encoder.embeddings.patch_embeddings.projection.weight"""), ("""encoder.deit.patch_embed.proj.bias""", """encoder.embeddings.patch_embeddings.projection.bias"""), ("""encoder.deit.norm.weight""", """encoder.layernorm.weight"""), ("""encoder.deit.norm.bias""", """encoder.layernorm.bias"""), ] ) return rename_keys def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> Dict: """simple docstring""" for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) _SCREAMING_SNAKE_CASE = state_dict.pop(F'encoder.deit.blocks.{i}.attn.qkv.weight' ) _SCREAMING_SNAKE_CASE = in_proj_weight[ : encoder_config.hidden_size, : ] _SCREAMING_SNAKE_CASE = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] _SCREAMING_SNAKE_CASE = in_proj_weight[ -encoder_config.hidden_size :, : ] def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = dct.pop(snake_case__ ) _SCREAMING_SNAKE_CASE = val def __lowerCamelCase ( snake_case__ ) -> Union[str, Any]: """simple docstring""" if "handwritten" in checkpoint_url: _SCREAMING_SNAKE_CASE = """https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg""" # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: _SCREAMING_SNAKE_CASE = """https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg""" _SCREAMING_SNAKE_CASE = Image.open(requests.get(snake_case__ ,stream=snake_case__ ).raw ).convert("""RGB""" ) return im @torch.no_grad() def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE = ViTConfig(image_size=3_84 ,qkv_bias=snake_case__ ) _SCREAMING_SNAKE_CASE = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: _SCREAMING_SNAKE_CASE = 7_68 elif "large" in checkpoint_url: # use ViT-large encoder _SCREAMING_SNAKE_CASE = 10_24 _SCREAMING_SNAKE_CASE = 40_96 _SCREAMING_SNAKE_CASE = 24 _SCREAMING_SNAKE_CASE = 16 _SCREAMING_SNAKE_CASE = 10_24 else: raise ValueError("""Should either find 'base' or 'large' in checkpoint URL""" ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = """relu""" _SCREAMING_SNAKE_CASE = 10_24 _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False # load HuggingFace model _SCREAMING_SNAKE_CASE = ViTModel(snake_case__ ,add_pooling_layer=snake_case__ ) _SCREAMING_SNAKE_CASE = TrOCRForCausalLM(snake_case__ ) _SCREAMING_SNAKE_CASE = VisionEncoderDecoderModel(encoder=snake_case__ ,decoder=snake_case__ ) model.eval() # load state_dict of original model, rename some keys _SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(snake_case__ ,map_location="""cpu""" ,check_hash=snake_case__ )["""model"""] _SCREAMING_SNAKE_CASE = create_rename_keys(snake_case__ ,snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ ,snake_case__ ,snake_case__ ) read_in_q_k_v(snake_case__ ,snake_case__ ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): _SCREAMING_SNAKE_CASE = state_dict.pop(snake_case__ ) if key.startswith("""decoder""" ) and "output_projection" not in key: _SCREAMING_SNAKE_CASE = val else: _SCREAMING_SNAKE_CASE = val # load state dict model.load_state_dict(snake_case__ ) # Check outputs on an image _SCREAMING_SNAKE_CASE = ViTImageProcessor(size=encoder_config.image_size ) _SCREAMING_SNAKE_CASE = RobertaTokenizer.from_pretrained("""roberta-large""" ) _SCREAMING_SNAKE_CASE = TrOCRProcessor(snake_case__ ,snake_case__ ) _SCREAMING_SNAKE_CASE = processor(images=prepare_img(snake_case__ ) ,return_tensors="""pt""" ).pixel_values # verify logits _SCREAMING_SNAKE_CASE = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) _SCREAMING_SNAKE_CASE = model(pixel_values=snake_case__ ,decoder_input_ids=snake_case__ ) _SCREAMING_SNAKE_CASE = outputs.logits _SCREAMING_SNAKE_CASE = torch.Size([1, 1, 5_02_65] ) if "trocr-base-handwritten" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor( [-1.4_502, -4.6_683, -0.5_347, -2.9_291, 9.1_435, -3.0_571, 8.9_764, 1.7_560, 8.7_358, -1.5_311] ) elif "trocr-large-handwritten" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor( [-2.6_437, -1.3_129, -2.2_596, -5.3_455, 6.3_539, 1.7_604, 5.4_991, 1.4_702, 5.6_113, 2.0_170] ) elif "trocr-base-printed" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor( [-5.6_816, -5.8_388, 1.1_398, -6.9_034, 6.8_505, -2.4_393, 1.2_284, -1.0_232, -1.9_661, -3.9_210] ) elif "trocr-large-printed" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor( [-6.0_162, -7.0_959, 4.4_155, -5.1_063, 7.0_468, -3.1_631, 2.6_466, -0.3_081, -0.8_106, -1.7_535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10] ,snake_case__ ,atol=1e-3 ), "First elements of logits not as expected" Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F'Saving model 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 __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_url''', default='''https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt''', type=str, help='''URL to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) UpperCamelCase = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
125
0
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 SCREAMING_SNAKE_CASE :Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :List[Any] = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "yolos" def __init__( self : Any ,A : Optional[Any]=7_68 ,A : Dict=12 ,A : Any=12 ,A : str=30_72 ,A : Any="gelu" ,A : str=0.0 ,A : List[str]=0.0 ,A : Dict=0.02 ,A : int=1E-12 ,A : Tuple=[5_12, 8_64] ,A : List[Any]=16 ,A : str=3 ,A : str=True ,A : Any=1_00 ,A : Dict=True ,A : Dict=False ,A : Tuple=1 ,A : Union[str, Any]=5 ,A : Optional[Any]=2 ,A : Union[str, Any]=5 ,A : int=2 ,A : int=0.1 ,**A : List[str] ,): super().__init__(**A ) __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = initializer_range __A = layer_norm_eps __A = image_size __A = patch_size __A = num_channels __A = qkv_bias __A = num_detection_tokens __A = use_mid_position_embeddings __A = auxiliary_loss # Hungarian matcher __A = class_cost __A = bbox_cost __A = giou_cost # Loss coefficients __A = bbox_loss_coefficient __A = giou_loss_coefficient __A = eos_coefficient class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.11" ) @property def UpperCamelCase_ ( self : str ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase_ ( self : List[Any] ): return 1E-4 @property def UpperCamelCase_ ( self : Optional[Any] ): return 12
15
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class __UpperCAmelCase : def __init__( self: Union[str, Any] , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: int=13 , UpperCAmelCase_: Optional[int]=7 , UpperCAmelCase_: List[str]=False , UpperCAmelCase_: str=True , UpperCAmelCase_: Union[str, Any]=False , UpperCAmelCase_: Optional[Any]=True , UpperCAmelCase_: Optional[int]=33 , UpperCAmelCase_: Tuple=32 , UpperCAmelCase_: List[Any]=5 , UpperCAmelCase_: Union[str, Any]=4 , UpperCAmelCase_: Any=37 , UpperCAmelCase_: Optional[Any]="gelu" , UpperCAmelCase_: Dict=0.1 , UpperCAmelCase_: List[Any]=0.1 , UpperCAmelCase_: Dict=512 , UpperCAmelCase_: int=16 , UpperCAmelCase_: Optional[Any]=2 , UpperCAmelCase_: Optional[Any]=0.02 , UpperCAmelCase_: Tuple=3 , UpperCAmelCase_: Union[str, Any]=4 , UpperCAmelCase_: str=None , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = seq_length _SCREAMING_SNAKE_CASE = is_training _SCREAMING_SNAKE_CASE = use_input_mask _SCREAMING_SNAKE_CASE = use_token_type_ids _SCREAMING_SNAKE_CASE = use_labels _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = type_sequence_label_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = num_labels _SCREAMING_SNAKE_CASE = num_choices _SCREAMING_SNAKE_CASE = scope def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE = None if self.use_input_mask: _SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None if self.use_labels: _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase ( self: List[Any] ): '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCamelCase ( self: Dict , UpperCAmelCase_: List[Any] , UpperCAmelCase_: Optional[Any] , UpperCAmelCase_: str , UpperCAmelCase_: List[str] , UpperCAmelCase_: Tuple , UpperCAmelCase_: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = EsmModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = 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 UpperCamelCase ( self: List[Any] , UpperCAmelCase_: List[str] , UpperCAmelCase_: int , UpperCAmelCase_: int , UpperCAmelCase_: int , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: Any ): '''simple docstring''' _SCREAMING_SNAKE_CASE = EsmForMaskedLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase ( self: List[Any] , UpperCAmelCase_: int , UpperCAmelCase_: List[str] , UpperCAmelCase_: str , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: Tuple , UpperCAmelCase_: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.num_labels _SCREAMING_SNAKE_CASE = EsmForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) = config_and_inputs _SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __UpperCAmelCase (_UpperCAmelCase ,_UpperCAmelCase ,unittest.TestCase ): __snake_case : List[Any] = False __snake_case : Dict = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __snake_case : List[Any] = () __snake_case : Dict = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __snake_case : int = True def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = EsmModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def UpperCamelCase ( self: int ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self: Tuple ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def UpperCamelCase ( self: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase_ ) def UpperCamelCase ( self: Any ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) @slow def UpperCamelCase ( self: int ): '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE = EsmModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def UpperCamelCase ( self: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()[0] _SCREAMING_SNAKE_CASE = EsmEmbeddings(config=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) _SCREAMING_SNAKE_CASE = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _SCREAMING_SNAKE_CASE = create_position_ids_from_input_ids(UpperCAmelCase_ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(UpperCAmelCase_ , UpperCAmelCase_ ) ) ) def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()[0] _SCREAMING_SNAKE_CASE = EsmEmbeddings(config=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = torch.empty(2 , 4 , 30 ) _SCREAMING_SNAKE_CASE = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _SCREAMING_SNAKE_CASE = torch.as_tensor([expected_single_positions, expected_single_positions] ) _SCREAMING_SNAKE_CASE = embeddings.create_position_ids_from_inputs_embeds(UpperCAmelCase_ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(UpperCAmelCase_ , UpperCAmelCase_ ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def UpperCamelCase ( self: Dict ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase ( self: Any ): '''simple docstring''' pass @require_torch class __UpperCAmelCase (_UpperCAmelCase ): @slow def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE = EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ )[0] _SCREAMING_SNAKE_CASE = 33 _SCREAMING_SNAKE_CASE = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = torch.tensor( [[[8.92_15, -10.58_98, -6.46_71], [-6.39_67, -13.91_14, -1.12_12], [-7.78_12, -13.95_16, -3.74_06]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def UpperCamelCase ( self: Dict ): '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE = EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _SCREAMING_SNAKE_CASE = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ )[0] # compare the actual values for a slice. _SCREAMING_SNAKE_CASE = torch.tensor( [[[0.14_44, 0.54_13, 0.32_48], [0.30_34, 0.00_53, 0.31_08], [0.32_28, -0.24_99, 0.34_15]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
306
0
'''simple docstring''' import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 _SCREAMING_SNAKE_CASE : Union[str, Any] = get_tests_dir("fixtures/dummy_feature_extractor_config.json") _SCREAMING_SNAKE_CASE : Tuple = get_tests_dir("fixtures/vocab.json") _SCREAMING_SNAKE_CASE : Optional[Any] = get_tests_dir("fixtures") class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" snake_case_ = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] def lowerCAmelCase ( self : str )-> Any: snake_case = 0 def lowerCAmelCase ( self : Tuple )-> Optional[Any]: snake_case = AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(__snake_case , __snake_case ) def lowerCAmelCase ( self : Dict )-> Union[str, Any]: with tempfile.TemporaryDirectory() as tmpdirname: snake_case = WavaVecaConfig() snake_case = AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) # save in new folder model_config.save_pretrained(__snake_case ) processor.save_pretrained(__snake_case ) snake_case = AutoProcessor.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowerCAmelCase ( self : int )-> str: with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(__snake_case , os.path.join(__snake_case , __snake_case ) ) copyfile(__snake_case , os.path.join(__snake_case , """vocab.json""" ) ) snake_case = AutoProcessor.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowerCAmelCase ( self : List[Any] )-> str: with tempfile.TemporaryDirectory() as tmpdirname: snake_case = WavaVecaFeatureExtractor() snake_case = AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) snake_case = WavaVecaProcessor(__snake_case , __snake_case ) # save in new folder processor.save_pretrained(__snake_case ) # drop `processor_class` in tokenizer with open(os.path.join(__snake_case , __snake_case ) , """r""" ) as f: snake_case = json.load(__snake_case ) config_dict.pop("""processor_class""" ) with open(os.path.join(__snake_case , __snake_case ) , """w""" ) as f: f.write(json.dumps(__snake_case ) ) snake_case = AutoProcessor.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowerCAmelCase ( self : Dict )-> Optional[int]: with tempfile.TemporaryDirectory() as tmpdirname: snake_case = WavaVecaFeatureExtractor() snake_case = AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) snake_case = WavaVecaProcessor(__snake_case , __snake_case ) # save in new folder processor.save_pretrained(__snake_case ) # drop `processor_class` in feature extractor with open(os.path.join(__snake_case , __snake_case ) , """r""" ) as f: snake_case = json.load(__snake_case ) config_dict.pop("""processor_class""" ) with open(os.path.join(__snake_case , __snake_case ) , """w""" ) as f: f.write(json.dumps(__snake_case ) ) snake_case = AutoProcessor.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowerCAmelCase ( self : Optional[int] )-> str: with tempfile.TemporaryDirectory() as tmpdirname: snake_case = WavaVecaConfig(processor_class="""Wav2Vec2Processor""" ) model_config.save_pretrained(__snake_case ) # copy relevant files copyfile(__snake_case , os.path.join(__snake_case , """vocab.json""" ) ) # create emtpy sample processor with open(os.path.join(__snake_case , __snake_case ) , """w""" ) as f: f.write("""{}""" ) snake_case = AutoProcessor.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowerCAmelCase ( self : int )-> Any: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__snake_case ): snake_case = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__snake_case ): snake_case = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=__snake_case ) snake_case = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" , trust_remote_code=__snake_case ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) snake_case = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) snake_case = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version snake_case = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=__snake_case , use_fast=__snake_case ) snake_case = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def lowerCAmelCase ( self : List[Any] )-> List[Any]: try: AutoConfig.register("""custom""" , __snake_case ) AutoFeatureExtractor.register(__snake_case , __snake_case ) AutoTokenizer.register(__snake_case , slow_tokenizer_class=__snake_case ) AutoProcessor.register(__snake_case , __snake_case ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__snake_case ): AutoProcessor.register(__snake_case , __snake_case ) # Now that the config is registered, it can be used as any other config with the auto-API snake_case = CustomFeatureExtractor.from_pretrained(__snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: snake_case = os.path.join(__snake_case , """vocab.txt""" ) with open(__snake_case , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) snake_case = CustomTokenizer(__snake_case ) snake_case = CustomProcessor(__snake_case , __snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(__snake_case ) snake_case = AutoProcessor.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCAmelCase ( self : Any )-> Tuple: class _lowerCAmelCase ( A__ ): """simple docstring""" snake_case_ = False class _lowerCAmelCase ( A__ ): """simple docstring""" snake_case_ = False class _lowerCAmelCase ( A__ ): """simple docstring""" snake_case_ = "AutoFeatureExtractor" snake_case_ = "AutoTokenizer" snake_case_ = False try: AutoConfig.register("""custom""" , __snake_case ) AutoFeatureExtractor.register(__snake_case , __snake_case ) AutoTokenizer.register(__snake_case , slow_tokenizer_class=__snake_case ) AutoProcessor.register(__snake_case , __snake_case ) # If remote code is not set, the default is to use local classes. snake_case = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. snake_case = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=__snake_case ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. snake_case = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=__snake_case ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCAmelCase ( self : str )-> Union[str, Any]: snake_case = AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(processor.__class__.__name__ , """BertTokenizerFast""" ) def lowerCAmelCase ( self : Any )-> List[str]: snake_case = AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-convnext""" ) self.assertEqual(processor.__class__.__name__ , """ConvNextImageProcessor""" ) @is_staging_test class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" snake_case_ = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def lowerCAmelCase ( cls : Optional[Any] )-> Tuple: snake_case = TOKEN HfFolder.save_token(__snake_case ) @classmethod def lowerCAmelCase ( cls : Optional[Any] )-> Optional[Any]: try: delete_repo(token=cls._token , repo_id="""test-processor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-processor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-processor""" ) except HTTPError: pass def lowerCAmelCase ( self : List[Any] )-> str: snake_case = WavaVecaProcessor.from_pretrained(__snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(__snake_case , """test-processor""" ) , push_to_hub=__snake_case , use_auth_token=self._token ) snake_case = WavaVecaProcessor.from_pretrained(f'''{USER}/test-processor''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(__snake_case , getattr(new_processor.feature_extractor , __snake_case ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def lowerCAmelCase ( self : Any )-> Optional[Any]: snake_case = WavaVecaProcessor.from_pretrained(__snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(__snake_case , """test-processor-org""" ) , push_to_hub=__snake_case , use_auth_token=self._token , organization="""valid_org""" , ) snake_case = WavaVecaProcessor.from_pretrained("""valid_org/test-processor-org""" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(__snake_case , getattr(new_processor.feature_extractor , __snake_case ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def lowerCAmelCase ( self : List[str] )-> int: CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() snake_case = CustomFeatureExtractor.from_pretrained(__snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: snake_case = os.path.join(__snake_case , """vocab.txt""" ) with open(__snake_case , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) snake_case = CustomTokenizer(__snake_case ) snake_case = CustomProcessor(__snake_case , __snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(f'''{USER}/test-dynamic-processor''' , token=self._token ) snake_case = Repository(__snake_case , clone_from=f'''{USER}/test-dynamic-processor''' , token=self._token ) processor.save_pretrained(__snake_case ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { """AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor""", """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(__snake_case , """tokenizer_config.json""" ) ) as f: snake_case = json.load(__snake_case ) self.assertDictEqual( tokenizer_config["""auto_map"""] , { """AutoTokenizer""": ["""custom_tokenization.CustomTokenizer""", None], """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(__snake_case , """custom_feature_extraction.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(__snake_case , """custom_tokenization.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(__snake_case , """custom_processing.py""" ) ) ) repo.push_to_hub() snake_case = AutoProcessor.from_pretrained(f'''{USER}/test-dynamic-processor''' , trust_remote_code=__snake_case ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , """CustomProcessor""" )
357
'''simple docstring''' import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __lowerCamelCase ( __lowerCAmelCase : dict ) -> tuple: return (data["data"], data["target"]) def __lowerCamelCase ( __lowerCAmelCase : np.ndarray , __lowerCAmelCase : np.ndarray ) -> XGBClassifier: snake_case = XGBClassifier() classifier.fit(__lowerCAmelCase , __lowerCAmelCase ) return classifier def __lowerCamelCase ( ) -> None: snake_case = load_iris() snake_case , snake_case = data_handling(__lowerCAmelCase ) snake_case , snake_case , snake_case , snake_case = train_test_split( __lowerCAmelCase , __lowerCAmelCase , test_size=0.25 ) snake_case = iris["""target_names"""] # Create an XGBoost Classifier from the training data snake_case = xgboost(__lowerCAmelCase , __lowerCAmelCase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , display_labels=__lowerCAmelCase , cmap="""Blues""" , normalize="""true""" , ) plt.title("""Normalized Confusion Matrix - IRIS Dataset""" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
3
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
97
def A_ ( ) -> list[list[int]]: '''simple docstring''' return [list(range(1000 - i , -1000 - i , -1 ) ) for i in range(1000 )] lowercase__ : List[str] = generate_large_matrix() lowercase__ : Tuple = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def A_ ( snake_case : list[list[int]] ) -> None: '''simple docstring''' assert all(row == sorted(snake_case , reverse=snake_case ) for row in grid ) assert all(list(snake_case ) == sorted(snake_case , reverse=snake_case ) for col in zip(*snake_case ) ) def A_ ( snake_case : list[int] ) -> int: '''simple docstring''' __UpperCamelCase = 0 __UpperCamelCase = len(snake_case ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: __UpperCamelCase = (left + right) // 2 __UpperCamelCase = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: __UpperCamelCase = mid + 1 else: __UpperCamelCase = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(snake_case ) def A_ ( snake_case : list[list[int]] ) -> int: '''simple docstring''' __UpperCamelCase = 0 __UpperCamelCase = len(grid[0] ) for i in range(len(snake_case ) ): __UpperCamelCase = find_negative_index(grid[i][:bound] ) total += bound return (len(snake_case ) * len(grid[0] )) - total def A_ ( snake_case : list[list[int]] ) -> int: '''simple docstring''' return len([number for row in grid for number in row if number < 0] ) def A_ ( snake_case : list[list[int]] ) -> int: '''simple docstring''' __UpperCamelCase = 0 for row in grid: for i, number in enumerate(snake_case ): if number < 0: total += len(snake_case ) - i break return total def A_ ( ) -> None: '''simple docstring''' from timeit import timeit print('''Running benchmarks''' ) __UpperCamelCase = ( '''from __main__ import count_negatives_binary_search, ''' '''count_negatives_brute_force, count_negatives_brute_force_with_break, grid''' ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): __UpperCamelCase = timeit(f"{func}(grid=grid)" , setup=snake_case , number=500 ) print(f"{func}() took {time:0.4f} seconds" ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
328
0
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed lowercase_ = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(f"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) lowercase_ = "sshleifer/student_marian_en_ro_6_1" lowercase_ = "sshleifer/tiny-mbart" @require_torch class A ( _UpperCAmelCase ): """simple docstring""" def snake_case__ ( self : List[Any],lowercase_ : List[str]=False,lowercase_ : Any=None,lowercase_ : Union[str, Any]=True,lowercase_ : List[str]=True,lowercase_ : Optional[Any]=True,lowercase_ : Dict=True,)-> Optional[int]: '''simple docstring''' A__ = self.run_trainer( eval_steps=1,max_len=1_2,model_name=lowercase_,num_train_epochs=1,distributed=lowercase_,extra_args_str=lowercase_,predict_with_generate=lowercase_,do_train=lowercase_,do_eval=lowercase_,do_predict=lowercase_,) A__ = TrainerState.load_from_json(os.path.join(lowercase_,'trainer_state.json' ) ).log_history if not do_eval: return A__ = [log for log in logs if 'eval_loss' in log.keys()] A__ = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A__ = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'],lowercase_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def snake_case__ ( self : int )-> Any: '''simple docstring''' self.run_seqaseq_quick() @require_torch_multi_gpu def snake_case__ ( self : Dict )-> Any: '''simple docstring''' self.run_seqaseq_quick(distributed=lowercase_ ) @require_torch_multi_gpu def snake_case__ ( self : Union[str, Any] )-> List[Any]: '''simple docstring''' self.run_seqaseq_quick(distributed=lowercase_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def snake_case__ ( self : List[Any] )-> Optional[Any]: '''simple docstring''' self.run_seqaseq_quick(distributed=lowercase_,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def snake_case__ ( self : Tuple )-> int: '''simple docstring''' self.run_seqaseq_quick(distributed=lowercase_,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def snake_case__ ( self : List[Any] )-> List[Any]: '''simple docstring''' self.run_seqaseq_quick(distributed=lowercase_,extra_args_str='--sharded_ddp zero_dp_2',predict_with_generate=lowercase_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def snake_case__ ( self : List[Any] )-> Optional[Any]: '''simple docstring''' self.run_seqaseq_quick( distributed=lowercase_,extra_args_str='--sharded_ddp zero_dp_2 --fp16',predict_with_generate=lowercase_ ) @require_apex @require_torch_gpu def snake_case__ ( self : Union[str, Any] )-> List[str]: '''simple docstring''' self.run_seqaseq_quick(distributed=lowercase_,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=lowercase_,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def snake_case__ ( self : List[Any],lowercase_ : List[Any] )-> List[str]: '''simple docstring''' A__ = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A__ = experiments[experiment_id] A__ = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A__ = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**lowercase_,extra_args_str=data['extra_args_str'] ) A__ = len(re.findall(lowercase_,cl.err ) ) self.assertEqual(lowercase_,data['n_matches'] ) @slow def snake_case__ ( self : Tuple )-> Union[str, Any]: '''simple docstring''' A__ = self.run_trainer( eval_steps=2,max_len=1_2_8,model_name=lowercase_,learning_rate=3E-4,num_train_epochs=1_0,distributed=lowercase_,) # Check metrics A__ = TrainerState.load_from_json(os.path.join(lowercase_,'trainer_state.json' ) ).log_history A__ = [log for log in logs if 'eval_loss' in log.keys()] A__ = eval_metrics[0] A__ = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'],lowercase_ ) # test if do_predict saves generations and metrics A__ = os.listdir(lowercase_ ) A__ = {os.path.basename(lowercase_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def snake_case__ ( self : List[str] )-> Optional[int]: '''simple docstring''' from transformers.training_args import OptimizerNames def train_and_return_metrics(lowercase_ : str ) -> Tuple[int, float]: A__ = '--skip_memory_metrics 0' A__ = self.run_trainer( max_len=1_2_8,model_name=lowercase_,learning_rate=3E-4,num_train_epochs=1,optim=lowercase_,distributed=lowercase_,extra_args_str=lowercase_,do_eval=lowercase_,do_predict=lowercase_,n_gpus_to_use=1,) # Check metrics A__ = TrainerState.load_from_json(Path(lowercase_,'trainer_state.json' ) ).log_history A__ = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**2_0 ) A__ = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**2_0 ) A__ = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A__ , A__ , A__ = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A__ , A__ , A__ = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A__ = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A__ = gpu_peak_mem_orig + gpu_alloc_mem_orig A__ = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A__ = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A__ = 1_2_0 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( lowercase_,lowercase_,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB',) self.assertGreater( lowercase_,lowercase_,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB',) self.assertEqual( lowercase_,lowercase_,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def snake_case__ ( self : Any,lowercase_ : int,lowercase_ : str,lowercase_ : int,lowercase_ : float = 3E-3,lowercase_ : str = "adafactor",lowercase_ : bool = False,lowercase_ : str = None,lowercase_ : int = 0,lowercase_ : bool = True,lowercase_ : bool = True,lowercase_ : bool = True,lowercase_ : bool = True,lowercase_ : int = None,)-> Optional[int]: '''simple docstring''' A__ = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A__ = self.get_auto_remove_tmp_dir() A__ = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(lowercase_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(lowercase_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A__ = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(lowercase_ )}\n '.split() A__ = '\n --do_predict\n '.split() A__ = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A__ = get_gpu_count() A__ = get_torch_dist_unique_port() A__ = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A__ = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(lowercase_,env=self.get_env() ) else: A__ = ['run_translation.py'] + args with patch.object(lowercase_,'argv',lowercase_ ): main() return output_dir
282
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path lowercase_ = Path(__file__).resolve().parents[3] / "src" sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) lowercase_ = {"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"} lowercase_ = "zero2" lowercase_ = "zero3" lowercase_ = [ZEROa, ZEROa] def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Dict: '''simple docstring''' A__ = parameterized.to_safe_name('_'.join(str(SCREAMING_SNAKE_CASE__ ) for x in param.args ) ) return f'{func.__name__}_{param_based_name}' # Cartesian-product of zero stages with models to test lowercase_ = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class A ( _UpperCAmelCase ): """simple docstring""" @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : int,lowercase_ : str,lowercase_ : Any )-> Optional[int]: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) @require_torch_multi_gpu @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : Union[str, Any],lowercase_ : Optional[Any],lowercase_ : List[Any] )-> int: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : List[str],lowercase_ : List[str],lowercase_ : List[Any] )-> Any: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) @require_torch_multi_gpu @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : Dict,lowercase_ : Optional[Any],lowercase_ : List[Any] )-> Optional[int]: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) def snake_case__ ( self : Tuple,lowercase_ : Any )-> Union[str, Any]: '''simple docstring''' pass def snake_case__ ( self : int,lowercase_ : str,lowercase_ : str,lowercase_ : int = 1_0,lowercase_ : bool = True,lowercase_ : bool = True,lowercase_ : bool = True,)-> Union[str, Any]: '''simple docstring''' A__ = models[model] A__ = self.run_trainer( stage=lowercase_,model_name=lowercase_,eval_steps=lowercase_,num_train_epochs=1,distributed=lowercase_,fpaa=lowercase_,) self.do_checks(lowercase_ ) return output_dir def snake_case__ ( self : Union[str, Any],lowercase_ : str,lowercase_ : str,lowercase_ : int = 1_0,lowercase_ : int = 1,lowercase_ : bool = True,lowercase_ : bool = True,)-> Any: '''simple docstring''' A__ = self.get_auto_remove_tmp_dir('./xxx',after=lowercase_ ) A__ = F'\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(lowercase_ )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n '.split() if fpaa: args.extend(['--fp16'] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files A__ = F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split() A__ = [F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py'] A__ = self.get_launcher(lowercase_ ) A__ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(lowercase_,env=self.get_env() ) return output_dir def snake_case__ ( self : Any,lowercase_ : int=False )-> Tuple: '''simple docstring''' A__ = min(2,get_gpu_count() ) if distributed else 1 return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()
282
1
def __UpperCAmelCase ( __a : int ) -> Optional[int]: """simple docstring""" return sum(i for i in range(1 ,number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print('''Program to check whether a number is a Perfect number or not...''') a__ = int(input('''Enter number: ''').strip()) print(f'''{number} is {"" if perfect(number) else "not "}a Perfect Number.''')
235
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase = { """configuration_roberta""": ["""ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RobertaConfig""", """RobertaOnnxConfig"""], """tokenization_roberta""": ["""RobertaTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ["""RobertaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """RobertaForCausalLM""", """RobertaForMaskedLM""", """RobertaForMultipleChoice""", """RobertaForQuestionAnswering""", """RobertaForSequenceClassification""", """RobertaForTokenClassification""", """RobertaModel""", """RobertaPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFRobertaForCausalLM""", """TFRobertaForMaskedLM""", """TFRobertaForMultipleChoice""", """TFRobertaForQuestionAnswering""", """TFRobertaForSequenceClassification""", """TFRobertaForTokenClassification""", """TFRobertaMainLayer""", """TFRobertaModel""", """TFRobertaPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """FlaxRobertaForCausalLM""", """FlaxRobertaForMaskedLM""", """FlaxRobertaForMultipleChoice""", """FlaxRobertaForQuestionAnswering""", """FlaxRobertaForSequenceClassification""", """FlaxRobertaForTokenClassification""", """FlaxRobertaModel""", """FlaxRobertaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
186
0
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : Optional[int] ) -> str: __lowerCAmelCase = get_activation('swish' ) self.assertIsInstance(lowerCAmelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 ) def lowercase ( self : Dict ) -> Any: __lowerCAmelCase = get_activation('silu' ) self.assertIsInstance(lowerCAmelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 ) def lowercase ( self : Union[str, Any] ) -> List[str]: __lowerCAmelCase = get_activation('mish' ) self.assertIsInstance(lowerCAmelCase_ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 ) def lowercase ( self : Union[str, Any] ) -> Any: __lowerCAmelCase = get_activation('gelu' ) self.assertIsInstance(lowerCAmelCase_ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 )
207
import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : List[str] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowercase ( self : Union[str, Any] ) -> Any: torch.manual_seed(0 ) __lowerCAmelCase = UNetaDModel( sample_size=(3_2, 6_4) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def lowercase ( self : Optional[Any] ) -> List[Any]: torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=1_0 , ) return model @property def lowercase ( self : Dict ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL( sample_size=(1_2_8, 6_4) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) __lowerCAmelCase = UNetaDModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def lowercase ( self : Dict ) -> Optional[Any]: __lowerCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __lowerCAmelCase = DDPMScheduler() __lowerCAmelCase = AudioDiffusionPipeline(vqvae=lowerCAmelCase_ , unet=self.dummy_unet , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ , steps=4 ) __lowerCAmelCase = output.audios[0] __lowerCAmelCase = output.images[0] __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ , steps=4 , return_dict=lowerCAmelCase_ ) __lowerCAmelCase = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __lowerCAmelCase = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __lowerCAmelCase = DDIMScheduler() __lowerCAmelCase = self.dummy_vqvae_and_unet __lowerCAmelCase = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) np.random.seed(0 ) __lowerCAmelCase = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(raw_audio=lowerCAmelCase_ , generator=lowerCAmelCase_ , start_step=5 , steps=1_0 ) __lowerCAmelCase = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __lowerCAmelCase = self.dummy_unet_condition __lowerCAmelCase = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=lowerCAmelCase_ , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) np.random.seed(0 ) __lowerCAmelCase = torch.rand((1, 1, 1_0) ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ , encoding=lowerCAmelCase_ ) __lowerCAmelCase = output.images[0] __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : List[Any] ) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : Union[str, Any] ) -> Optional[int]: __lowerCAmelCase = torch_device __lowerCAmelCase = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ ) __lowerCAmelCase = output.audios[0] __lowerCAmelCase = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
207
1
import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def snake_case_ ( snake_case , snake_case , snake_case ) -> List[Any]: # Initialise PyTorch model lowercase__: Union[str, Any] = MobileBertConfig.from_json_file(snake_case ) print(f'Building PyTorch model from configuration: {config}' ) lowercase__: Tuple = MobileBertForPreTraining(snake_case ) # Load weights from tf checkpoint lowercase__: Union[str, Any] = load_tf_weights_in_mobilebert(snake_case , snake_case , snake_case ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , snake_case ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--mobilebert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained MobileBERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __lowerCAmelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
196
__lowerCAmelCase = range(2, 20 + 1) __lowerCAmelCase = [10**k for k in range(ks[-1] + 1)] __lowerCAmelCase = {} def snake_case_ ( snake_case , snake_case , snake_case , snake_case ) -> Optional[int]: lowercase__: str = sum(a_i[j] for j in range(snake_case , len(snake_case ) ) ) lowercase__: Optional[int] = sum(a_i[j] * base[j] for j in range(min(len(snake_case ) , snake_case ) ) ) lowercase__ , lowercase__: str = 0, 0 lowercase__: Tuple = n - i lowercase__: Dict = memo.get(snake_case ) if sub_memo is not None: lowercase__: Optional[Any] = sub_memo.get(snake_case ) if jumps is not None and len(snake_case ) > 0: # find and make the largest jump without going over lowercase__: int = -1 for _k in range(len(snake_case ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: lowercase__: Union[str, Any] = _k break if max_jump >= 0: lowercase__ , lowercase__ , lowercase__: Any = jumps[max_jump] # since the difference between jumps is cached, add c lowercase__: str = diff + c for j in range(min(snake_case , len(snake_case ) ) ): lowercase__ , lowercase__: Dict = divmod(snake_case , 10 ) if new_c > 0: add(snake_case , snake_case , snake_case ) else: lowercase__: List[Any] = [] else: lowercase__: Optional[Any] = {c: []} lowercase__: Union[str, Any] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps lowercase__ , lowercase__: Union[str, Any] = next_term(snake_case , k - 1 , i + dn , snake_case ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead lowercase__ , lowercase__: Dict = compute(snake_case , snake_case , i + dn , snake_case ) diff += _diff dn += terms_jumped lowercase__: Any = sub_memo[c] # keep jumps sorted by # of terms skipped lowercase__: str = 0 while j < len(snake_case ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(snake_case , (diff, dn, k) ) return (diff, dn) def snake_case_ ( snake_case , snake_case , snake_case , snake_case ) -> str: if i >= n: return 0, i if k > len(snake_case ): a_i.extend([0 for _ in range(k - len(snake_case ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) lowercase__: List[Any] = i lowercase__ , lowercase__ , lowercase__: Any = 0, 0, 0 for j in range(len(snake_case ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 lowercase__: str = ds_c + ds_b diff += addend lowercase__: List[str] = 0 for j in range(snake_case ): lowercase__: Any = a_i[j] + addend lowercase__ , lowercase__: List[Any] = divmod(snake_case , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(snake_case , snake_case , snake_case ) return diff, i - start_i def snake_case_ ( snake_case , snake_case , snake_case ) -> int: for j in range(snake_case , len(snake_case ) ): lowercase__: str = digits[j] + addend if s >= 10: lowercase__ , lowercase__: Any = divmod(snake_case , 10 ) lowercase__: Any = addend // 10 + quotient else: lowercase__: Union[str, Any] = s lowercase__: Union[str, Any] = addend // 10 if addend == 0: break while addend > 0: lowercase__ , lowercase__: Union[str, Any] = divmod(snake_case , 10 ) digits.append(snake_case ) def snake_case_ ( snake_case = 10**15 ) -> int: lowercase__: Optional[Any] = [1] lowercase__: int = 1 lowercase__: Tuple = 0 while True: lowercase__ , lowercase__: str = next_term(snake_case , 20 , i + dn , snake_case ) dn += terms_jumped if dn == n - i: break lowercase__: Dict = 0 for j in range(len(snake_case ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(F'''{solution() = }''')
196
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Dict = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[str] = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
215
"""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() lowerCamelCase_ : int = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) lowerCamelCase_ : Any = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'transformer.encoder.layers.{i}.self_attn.out_proj.weight', F'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (F'transformer.encoder.layers.{i}.self_attn.out_proj.bias', F'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.weight', F'encoder.layers.{i}.fc1.weight')) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.bias', F'encoder.layers.{i}.fc1.bias')) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.weight', F'encoder.layers.{i}.fc2.weight')) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.bias', F'encoder.layers.{i}.fc2.bias')) rename_keys.append( (F'transformer.encoder.layers.{i}.norm1.weight', F'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.norm1.bias', F'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((F'transformer.encoder.layers.{i}.norm2.weight', F'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((F'transformer.encoder.layers.{i}.norm2.bias', F'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F'transformer.decoder.layers.{i}.self_attn.out_proj.weight', F'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (F'transformer.decoder.layers.{i}.self_attn.out_proj.bias', F'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( F'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', F'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( F'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', F'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.weight', F'decoder.layers.{i}.fc1.weight')) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.bias', F'decoder.layers.{i}.fc1.bias')) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.weight', F'decoder.layers.{i}.fc2.weight')) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.bias', F'decoder.layers.{i}.fc2.bias')) rename_keys.append( (F'transformer.decoder.layers.{i}.norm1.weight', F'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm1.bias', F'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (F'transformer.decoder.layers.{i}.norm2.weight', F'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (F'transformer.decoder.layers.{i}.norm2.bias', F'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm3.weight', F'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((F'transformer.decoder.layers.{i}.norm3.bias', F'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("""input_proj.weight""", """input_projection.weight"""), ("""input_proj.bias""", """input_projection.bias"""), ("""query_embed.weight""", """query_position_embeddings.weight"""), ("""transformer.encoder.norm.weight""", """encoder.layernorm.weight"""), ("""transformer.encoder.norm.bias""", """encoder.layernorm.bias"""), ("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""), ("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""), ("""class_embed.weight""", """class_labels_classifier.weight"""), ("""class_embed.bias""", """class_labels_classifier.bias"""), ("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""), ("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""), ("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""), ("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""), ("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""), ("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""), ] ) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =state_dict.pop(lowercase ) a =val def _A ( lowercase ): """simple docstring""" a =OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: a =key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) a =value else: a =value return new_state_dict def _A ( lowercase ): """simple docstring""" a ='''''' # 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) a =state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) a =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 a =in_proj_weight[:2_56, :] a =in_proj_bias[:2_56] a =in_proj_weight[2_56:5_12, :] a =in_proj_bias[2_56:5_12] a =in_proj_weight[-2_56:, :] a =in_proj_bias[-2_56:] # 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 a =state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) a =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 a =in_proj_weight[:2_56, :] a =in_proj_bias[:2_56] a =in_proj_weight[2_56:5_12, :] a =in_proj_bias[2_56:5_12] a =in_proj_weight[-2_56:, :] a =in_proj_bias[-2_56:] # read in weights + bias of input projection layer of cross-attention a =state_dict.pop( f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) a =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 a =in_proj_weight_cross_attn[:2_56, :] a =in_proj_bias_cross_attn[:2_56] a =in_proj_weight_cross_attn[2_56:5_12, :] a =in_proj_bias_cross_attn[2_56:5_12] a =in_proj_weight_cross_attn[-2_56:, :] a =in_proj_bias_cross_attn[-2_56:] def _A ( lowercase , lowercase ): """simple docstring""" a , a =image.size a =max(lowercase , lowercase ) a =8_00 if '''detection''' in checkpoint_url else 10_00 a =target_max_size / current_max_size a =image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _A ( lowercase ): """simple docstring""" a =F.to_tensor(lowercase ) a =F.normalize(lowercase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _A ( lowercase , lowercase , lowercase ): """simple docstring""" logger.info('''Converting model...''' ) # load original state dict a =torch.hub.load_state_dict_from_url(lowercase , map_location='''cpu''' ) # rename keys for src, dest in rename_keys: rename_key(lowercase , lowercase , lowercase ) a =rename_backbone_keys(lowercase ) # query, key and value matrices need special treatment read_in_q_k_v(lowercase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them a ='''model.''' for key in state_dict.copy().keys(): if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): a =state_dict.pop(lowercase ) a =val # create HuggingFace model and load state dict a =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: a =15 a =2 a ={0: '''table''', 1: '''table rotated'''} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =1_25 a =6 a ={ 0: '''table''', 1: '''table column''', 2: '''table row''', 3: '''table column header''', 4: '''table projected row header''', 5: '''table spanning cell''', } a =idalabel a ={v: k for k, v in idalabel.items()} a =DetrImageProcessor( format='''coco_detection''' , max_size=8_00 if '''detection''' in checkpoint_url else 10_00 ) a =TableTransformerForObjectDetection(lowercase ) model.load_state_dict(lowercase ) model.eval() # verify our conversion a ='''example_pdf.png''' if '''detection''' in checkpoint_url else '''example_table.png''' a =hf_hub_download(repo_id='''nielsr/example-pdf''' , repo_type='''dataset''' , filename=lowercase ) a =Image.open(lowercase ).convert('''RGB''' ) a =normalize(resize(lowercase , lowercase ) ).unsqueeze(0 ) a =model(lowercase ) if "detection" in checkpoint_url: a =(1, 15, 3) a =torch.tensor( [[-6.7897, -16.9985, 6.7937], [-8.0186, -22.2192, 6.9677], [-7.3117, -21.0708, 7.4055]] ) a =torch.tensor([[0.4867, 0.1767, 0.6732], [0.6718, 0.4479, 0.3830], [0.4716, 0.1760, 0.6364]] ) else: a =(1, 1_25, 7) a =torch.tensor( [[-18.1430, -8.3214, 4.8274], [-18.4685, -7.1361, -4.2667], [-26.3693, -9.3429, -4.9962]] ) a =torch.tensor([[0.4983, 0.5595, 0.9440], [0.4916, 0.6315, 0.5954], [0.6108, 0.8637, 0.1135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , lowercase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , lowercase , 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(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) image_processor.save_pretrained(lowercase ) if push_to_hub: # Push model to HF hub logger.info('''Pushing model to the hub...''' ) a =( '''microsoft/table-transformer-detection''' if '''detection''' in checkpoint_url else '''microsoft/table-transformer-structure-recognition''' ) model.push_to_hub(lowercase ) image_processor.push_to_hub(lowercase ) if __name__ == "__main__": lowerCamelCase_ : Optional[int] = 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.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
215
1
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class A ( _UpperCAmelCase ): """simple docstring""" def __init__( self : str,lowercase_ : NestedDataStructureLike[PathLike],lowercase_ : Optional[NamedSplit] = None,lowercase_ : Optional[Features] = None,lowercase_ : str = None,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : Optional[str] = None,lowercase_ : Optional[int] = None,**lowercase_ : int,)-> Any: '''simple docstring''' super().__init__( lowercase_,split=lowercase_,features=lowercase_,cache_dir=lowercase_,keep_in_memory=lowercase_,streaming=lowercase_,num_proc=lowercase_,**lowercase_,) A__ = field A__ = path_or_paths if isinstance(lowercase_,lowercase_ ) else {self.split: path_or_paths} A__ = Json( cache_dir=lowercase_,data_files=lowercase_,features=lowercase_,field=lowercase_,**lowercase_,) def snake_case__ ( self : Any )-> str: '''simple docstring''' if self.streaming: A__ = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: A__ = None A__ = None A__ = None A__ = None self.builder.download_and_prepare( download_config=lowercase_,download_mode=lowercase_,verification_mode=lowercase_,base_path=lowercase_,num_proc=self.num_proc,) A__ = self.builder.as_dataset( split=self.split,verification_mode=lowercase_,in_memory=self.keep_in_memory ) return dataset class A : """simple docstring""" def __init__( self : Tuple,lowercase_ : Dataset,lowercase_ : Union[PathLike, BinaryIO],lowercase_ : Optional[int] = None,lowercase_ : Optional[int] = None,**lowercase_ : Tuple,)-> Union[str, Any]: '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(F'num_proc {num_proc} must be an integer > 0.' ) A__ = dataset A__ = path_or_buf A__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE A__ = num_proc A__ = 'utf-8' A__ = to_json_kwargs def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' A__ = self.to_json_kwargs.pop('path_or_buf',lowercase_ ) A__ = self.to_json_kwargs.pop('orient','records' ) A__ = self.to_json_kwargs.pop('lines',True if orient == 'records' else False ) A__ = self.to_json_kwargs.pop('index',False if orient in ['split', 'table'] else True ) A__ = self.to_json_kwargs.pop('compression',lowercase_ ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(F'`datasets` currently does not support {compression} compression' ) if isinstance(self.path_or_buf,(str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf,'wb',compression=lowercase_ ) as buffer: A__ = self._write(file_obj=lowercase_,orient=lowercase_,lines=lowercase_,index=lowercase_,**self.to_json_kwargs ) else: if compression: raise NotImplementedError( F'The compression parameter is not supported when writing to a buffer, but compression={compression}' ' was passed. Please provide a local path instead.' ) A__ = self._write( file_obj=self.path_or_buf,orient=lowercase_,lines=lowercase_,index=lowercase_,**self.to_json_kwargs ) return written def snake_case__ ( self : List[Any],lowercase_ : int )-> Dict: '''simple docstring''' A__ , A__ , A__ , A__ , A__ = args A__ = query_table( table=self.dataset.data,key=slice(lowercase_,offset + self.batch_size ),indices=self.dataset._indices,) A__ = batch.to_pandas().to_json( path_or_buf=lowercase_,orient=lowercase_,lines=lowercase_,index=lowercase_,**lowercase_ ) if not json_str.endswith('\n' ): json_str += "\n" return json_str.encode(self.encoding ) def snake_case__ ( self : Any,lowercase_ : BinaryIO,lowercase_ : Optional[Any],lowercase_ : Optional[int],lowercase_ : Optional[Any],**lowercase_ : Optional[Any],)-> int: '''simple docstring''' A__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0,len(self.dataset ),self.batch_size ),unit='ba',disable=not logging.is_progress_bar_enabled(),desc='Creating json from Arrow format',): A__ = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(lowercase_ ) else: A__ , A__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json,[(offset, orient, lines, index, to_json_kwargs) for offset in range(0,lowercase_,lowercase_ )],),total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size,unit='ba',disable=not logging.is_progress_bar_enabled(),desc='Creating json from Arrow format',): written += file_obj.write(lowercase_ ) return written
7
"""simple docstring""" def A ( snake_case :int , snake_case :int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
316
0
from __future__ import annotations from typing import Generic, TypeVar UpperCamelCase = TypeVar('T') class __lowerCamelCase ( Generic[T] ): """simple docstring""" def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : T ) -> None: lowerCAmelCase__ = data lowerCAmelCase__ = self lowerCAmelCase__ = 0 class __lowerCamelCase ( Generic[T] ): """simple docstring""" def __init__( self : str ) -> None: # map from node name to the node object lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : T ) -> None: # create a new set with x as its member lowerCAmelCase__ = DisjointSetTreeNode(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) lowerCAmelCase__ = self.map[data] if elem_ref != elem_ref.parent: lowerCAmelCase__ = self.find_set(elem_ref.parent.data ) return elem_ref.parent def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : DisjointSetTreeNode[T] , SCREAMING_SNAKE_CASE__ : DisjointSetTreeNode[T] ) -> None: # helper function for union operation if nodea.rank > nodea.rank: lowerCAmelCase__ = nodea else: lowerCAmelCase__ = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def a ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T ) -> None: # merge 2 disjoint sets self.link(self.find_set(SCREAMING_SNAKE_CASE__ ) , self.find_set(SCREAMING_SNAKE_CASE__ ) ) class __lowerCamelCase ( Generic[T] ): """simple docstring""" def __init__( self : List[str] ) -> None: # connections: map from the node to the neighbouring nodes (with weights) lowerCAmelCase__ = {} def a ( self : str , SCREAMING_SNAKE_CASE__ : T ) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: lowerCAmelCase__ = {} def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # add an edge with the given weight self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = weight lowerCAmelCase__ = weight def a ( self : Optional[Any] ) -> GraphUndirectedWeighted[T]: lowerCAmelCase__ = [] lowerCAmelCase__ = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda SCREAMING_SNAKE_CASE__ : x[2] ) # creating the disjoint set lowerCAmelCase__ = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(SCREAMING_SNAKE_CASE__ ) # MST generation lowerCAmelCase__ = 0 lowerCAmelCase__ = 0 lowerCAmelCase__ = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = edges[index] index += 1 lowerCAmelCase__ = disjoint_set.find_set(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = disjoint_set.find_set(SCREAMING_SNAKE_CASE__ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) disjoint_set.union(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return graph
221
from __future__ import annotations UpperCamelCase = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def _A ( lowerCAmelCase_ : list[list[int]] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : list[list[int]] , ): """simple docstring""" lowerCAmelCase__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the reference grid lowerCAmelCase__ = 1 lowerCAmelCase__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the action grid lowerCAmelCase__ = init[0] lowerCAmelCase__ = init[1] lowerCAmelCase__ = 0 lowerCAmelCase__ = g + heuristic[x][y] # cost from starting cell to destination cell lowerCAmelCase__ = [[f, g, x, y]] lowerCAmelCase__ = False # flag that is set when search is complete lowerCAmelCase__ = False # flag set if we can't find expand while not found and not resign: if len(lowerCAmelCase_ ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() lowerCAmelCase__ = cell.pop() lowerCAmelCase__ = next_cell[2] lowerCAmelCase__ = next_cell[3] lowerCAmelCase__ = next_cell[1] if x == goal[0] and y == goal[1]: lowerCAmelCase__ = True else: for i in range(len(lowerCAmelCase_ ) ): # to try out different valid actions lowerCAmelCase__ = x + DIRECTIONS[i][0] lowerCAmelCase__ = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(lowerCAmelCase_ ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: lowerCAmelCase__ = g + cost lowerCAmelCase__ = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) lowerCAmelCase__ = 1 lowerCAmelCase__ = i lowerCAmelCase__ = [] lowerCAmelCase__ = goal[0] lowerCAmelCase__ = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: lowerCAmelCase__ = x - DIRECTIONS[action[x][y]][0] lowerCAmelCase__ = y - DIRECTIONS[action[x][y]][1] lowerCAmelCase__ = xa lowerCAmelCase__ = ya invpath.append([x, y] ) lowerCAmelCase__ = [] for i in range(len(lowerCAmelCase_ ) ): path.append(invpath[len(lowerCAmelCase_ ) - 1 - i] ) return path, action if __name__ == "__main__": UpperCamelCase = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] UpperCamelCase = [0, 0] # all coordinates are given in format [y,x] UpperCamelCase = [len(grid) - 1, len(grid[0]) - 1] UpperCamelCase = 1 # the cost map which pushes the path closer to the goal UpperCamelCase = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): UpperCamelCase = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map UpperCamelCase = 99 UpperCamelCase , UpperCamelCase = search(grid, init, goal, cost, heuristic) print('ACTION MAP') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
221
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : int = { """configuration_upernet""": ["""UperNetConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[int] = [ """UperNetForSemanticSegmentation""", """UperNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys lowerCamelCase_ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
from collections.abc import Sequence from queue import Queue class a__ : def __init__( self : int,_A : List[Any],_A : Optional[Any],_A : Optional[int],_A : int=None,_A : List[str]=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = start SCREAMING_SNAKE_CASE_ : List[str] = end SCREAMING_SNAKE_CASE_ : Tuple = val SCREAMING_SNAKE_CASE_ : List[str] = (start + end) // 2 SCREAMING_SNAKE_CASE_ : Optional[int] = left SCREAMING_SNAKE_CASE_ : str = right def __repr__( self : Tuple ): """simple docstring""" return F'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class a__ : def __init__( self : Any,_A : Sequence,_A : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = collection SCREAMING_SNAKE_CASE_ : Optional[int] = function if self.collection: SCREAMING_SNAKE_CASE_ : List[str] = self._build_tree(0,len(_A ) - 1 ) def __UpperCamelCase ( self : int,_A : Any,_A : List[Any] ): """simple docstring""" self._update_tree(self.root,_A,_A ) def __UpperCamelCase ( self : str,_A : Any,_A : List[Any] ): """simple docstring""" return self._query_range(self.root,_A,_A ) def __UpperCamelCase ( self : Any,_A : Optional[int],_A : int ): """simple docstring""" if start == end: return SegmentTreeNode(_A,_A,self.collection[start] ) SCREAMING_SNAKE_CASE_ : List[Any] = (start + end) // 2 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._build_tree(_A,_A ) SCREAMING_SNAKE_CASE_ : Optional[int] = self._build_tree(mid + 1,_A ) return SegmentTreeNode(_A,_A,self.fn(left.val,right.val ),_A,_A ) def __UpperCamelCase ( self : int,_A : int,_A : Tuple,_A : Dict ): """simple docstring""" if node.start == i and node.end == i: SCREAMING_SNAKE_CASE_ : Union[str, Any] = val return if i <= node.mid: self._update_tree(node.left,_A,_A ) else: self._update_tree(node.right,_A,_A ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.fn(node.left.val,node.right.val ) def __UpperCamelCase ( self : str,_A : List[str],_A : Optional[int],_A : Optional[Any] ): """simple docstring""" if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left,_A,_A ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left,_A,node.mid ),self._query_range(node.right,node.mid + 1,_A ),) else: # range in right child tree return self._query_range(node.right,_A,_A ) def __UpperCamelCase ( self : Optional[Any] ): """simple docstring""" if self.root is not None: SCREAMING_SNAKE_CASE_ : int = Queue() queue.put(self.root ) while not queue.empty(): SCREAMING_SNAKE_CASE_ : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) __lowerCamelCase : int = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
18
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
233
"""simple docstring""" import math class __A : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : Tuple=0 ) ->Optional[int]: # a graph with Node 0,1,...,N-1 """simple docstring""" snake_case_ = n snake_case_ = [ [math.inf for j in range(0 , UpperCAmelCase_ )] for i in range(0 , UpperCAmelCase_ ) ] # adjacency matrix for weight snake_case_ = [ [math.inf for j in range(0 , UpperCAmelCase_ )] for i in range(0 , UpperCAmelCase_ ) ] # dp[i][j] stores minimum distance from i to j def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->Optional[int]: """simple docstring""" snake_case_ = w def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): snake_case_ = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Optional[int] = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
233
1
'''simple docstring''' import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def a ( __a , __a , __a ) -> List[str]: '''simple docstring''' return params[f'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :] def a ( __a , __a , __a , __a="attention" ) -> int: '''simple docstring''' UpperCamelCase__ :Any = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] ) UpperCamelCase__ :str = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) UpperCamelCase__ :int = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] ) UpperCamelCase__ :Any = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) UpperCamelCase__ :List[Any] = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] ) UpperCamelCase__ :Any = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) UpperCamelCase__ :Tuple = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] ) UpperCamelCase__ :Tuple = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def a ( __a , __a , __a , __a=False ) -> List[str]: '''simple docstring''' if split_mlp_wi: UpperCamelCase__ :Any = params[f'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :] UpperCamelCase__ :Any = params[f'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :] UpperCamelCase__ :List[Any] = (wi_a, wi_a) else: UpperCamelCase__ :Optional[Any] = params[f'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :] UpperCamelCase__ :Optional[int] = params[f'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :] return wi, wo def a ( __a , __a , __a , __a ) -> Union[str, Any]: '''simple docstring''' return params[f'''{prefix}/{prefix}/{layer_name}/scale'''][:, i] def a ( __a , *, __a , __a , __a = False ) -> str: '''simple docstring''' UpperCamelCase__ :str = traverse_util.flatten_dict(variables['''target'''] ) UpperCamelCase__ :Dict = {'''/'''.join(__a ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase__ :str = '''encoder/encoder/mlp/wi_0/kernel''' in old print('''Split MLP:''' , __a ) UpperCamelCase__ :Any = collections.OrderedDict() # Shared embeddings. UpperCamelCase__ :List[str] = old['''token_embedder/embedding'''] # Encoder. for i in range(__a ): # Block i, layer 0 (Self Attention). UpperCamelCase__ :Any = tax_layer_norm_lookup(__a , __a , '''encoder''' , '''pre_attention_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :List[str] = tax_attention_lookup(__a , __a , '''encoder''' , '''attention''' ) UpperCamelCase__ :str = layer_norm UpperCamelCase__ :int = k.T UpperCamelCase__ :Union[str, Any] = o.T UpperCamelCase__ :Optional[int] = q.T UpperCamelCase__ :Tuple = v.T # Block i, layer 1 (MLP). UpperCamelCase__ :Optional[Any] = tax_layer_norm_lookup(__a , __a , '''encoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ :str = tax_mlp_lookup(__a , __a , '''encoder''' , __a ) UpperCamelCase__ :Any = layer_norm if split_mlp_wi: UpperCamelCase__ :List[Any] = wi[0].T UpperCamelCase__ :Tuple = wi[1].T else: UpperCamelCase__ :Union[str, Any] = wi.T UpperCamelCase__ :List[str] = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase__ :List[str] = tax_relpos_bias_lookup( __a , __a , '''encoder''' ).T UpperCamelCase__ :str = old['''encoder/encoder_norm/scale'''] if not scalable_attention: UpperCamelCase__ :Optional[int] = tax_relpos_bias_lookup( __a , 0 , '''encoder''' ).T UpperCamelCase__ :int = tax_relpos_bias_lookup( __a , 0 , '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(__a ): # Block i, layer 0 (Self Attention). UpperCamelCase__ :Dict = tax_layer_norm_lookup(__a , __a , '''decoder''' , '''pre_self_attention_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :Optional[int] = tax_attention_lookup(__a , __a , '''decoder''' , '''self_attention''' ) UpperCamelCase__ :List[str] = layer_norm UpperCamelCase__ :Optional[int] = k.T UpperCamelCase__ :Union[str, Any] = o.T UpperCamelCase__ :Optional[int] = q.T UpperCamelCase__ :str = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase__ :Union[str, Any] = tax_layer_norm_lookup(__a , __a , '''decoder''' , '''pre_cross_attention_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :Union[str, Any] = tax_attention_lookup(__a , __a , '''decoder''' , '''encoder_decoder_attention''' ) UpperCamelCase__ :Tuple = layer_norm UpperCamelCase__ :List[str] = k.T UpperCamelCase__ :List[str] = o.T UpperCamelCase__ :str = q.T UpperCamelCase__ :str = v.T # Block i, layer 2 (MLP). UpperCamelCase__ :Tuple = tax_layer_norm_lookup(__a , __a , '''decoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ :Optional[int] = tax_mlp_lookup(__a , __a , '''decoder''' , __a ) UpperCamelCase__ :Dict = layer_norm if split_mlp_wi: UpperCamelCase__ :List[Any] = wi[0].T UpperCamelCase__ :Tuple = wi[1].T else: UpperCamelCase__ :Dict = wi.T UpperCamelCase__ :Optional[int] = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase__ :Any = tax_relpos_bias_lookup(__a , __a , '''decoder''' ).T UpperCamelCase__ :Dict = old['''decoder/decoder_norm/scale'''] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase__ :Tuple = old['''decoder/logits_dense/kernel'''].T return new def a ( __a , __a ) -> List[str]: '''simple docstring''' UpperCamelCase__ :str = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase__ :List[str] = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase__ :Tuple = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) UpperCamelCase__ :Tuple = state_dict['''shared.weight'''] return state_dict def a ( __a , __a , __a , __a , __a ) -> List[Any]: '''simple docstring''' UpperCamelCase__ :int = checkpoints.load_tax_checkpoint(__a ) UpperCamelCase__ :List[str] = convert_tax_to_pytorch( __a , num_layers=config.num_layers , is_encoder_only=__a , scalable_attention=__a ) UpperCamelCase__ :List[str] = make_state_dict(__a , __a ) model.load_state_dict(__a , strict=__a ) def a ( __a , __a , __a , __a = False , __a = False , ) -> List[Any]: '''simple docstring''' UpperCamelCase__ :int = MTaConfig.from_json_file(__a ) print(f'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase__ :Dict = UMTaEncoderModel(__a ) else: UpperCamelCase__ :Optional[int] = UMTaForConditionalGeneration(__a ) # Load weights from tf checkpoint load_tax_weights_in_ta(__a , __a , __a , __a , __a ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(__a ) # Verify that we can load the checkpoint. model.from_pretrained(__a ) print('''Done''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) __snake_case = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
97
"""simple docstring""" from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def __magic_name__ ( lowercase ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: List[str] =ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=lowercase ) SCREAMING_SNAKE_CASE_: List[Any] =parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(lowercase ) EnvironmentCommand.register_subcommand(lowercase ) TestCommand.register_subcommand(lowercase ) RunBeamCommand.register_subcommand(lowercase ) DummyDataCommand.register_subcommand(lowercase ) # Parse args SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_known_args() if not hasattr(lowercase , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE_: Dict =parse_unknown_args(lowercase ) # Run SCREAMING_SNAKE_CASE_: Tuple =args.func(lowercase , **lowercase ) service.run() if __name__ == "__main__": main()
173
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class SCREAMING_SNAKE_CASE_ ( __snake_case ): __lowerCAmelCase = """blenderbot-small""" __lowerCAmelCase = ["""past_key_values"""] __lowerCAmelCase = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Optional[int] , lowerCamelCase_ : str=5_0265 , lowerCamelCase_ : Optional[int]=512 , lowerCamelCase_ : Any=8 , lowerCamelCase_ : Any=2048 , lowerCamelCase_ : Union[str, Any]=16 , lowerCamelCase_ : Tuple=8 , lowerCamelCase_ : List[str]=2048 , lowerCamelCase_ : Tuple=16 , lowerCamelCase_ : int=0.0 , lowerCamelCase_ : Optional[Any]=0.0 , lowerCamelCase_ : Any=True , lowerCamelCase_ : Dict=True , lowerCamelCase_ : str="gelu" , lowerCamelCase_ : Union[str, Any]=512 , lowerCamelCase_ : str=0.1 , lowerCamelCase_ : Optional[Any]=0.0 , lowerCamelCase_ : List[str]=0.0 , lowerCamelCase_ : int=0.0_2 , lowerCamelCase_ : Dict=1 , lowerCamelCase_ : Dict=False , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : int=1 , lowerCamelCase_ : Any=2 , lowerCamelCase_ : str=2 , **lowerCamelCase_ : Tuple , ): """simple docstring""" UpperCamelCase = vocab_size UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = encoder_layerdrop UpperCamelCase = decoder_layerdrop UpperCamelCase = use_cache UpperCamelCase = encoder_layers UpperCamelCase = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , forced_eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) class SCREAMING_SNAKE_CASE_ ( __snake_case ): @property def lowerCamelCase_ ( self : str ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: UpperCamelCase = {0: "batch"} UpperCamelCase = {0: "batch", 1: "past_decoder_sequence + sequence"} else: UpperCamelCase = {0: "batch", 1: "decoder_sequence"} UpperCamelCase = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(UpperCamelCase__ , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: UpperCamelCase = self.num_layers for i in range(UpperCamelCase__ ): UpperCamelCase = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase = {0: "batch", 2: "past_sequence + sequence"} else: UpperCamelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}), ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}), ] ) return common_inputs @property def lowerCamelCase_ ( self : List[str] ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = super().outputs else: UpperCamelCase = super(UpperCamelCase__ , self ).outputs if self.use_past: UpperCamelCase = self.num_layers for i in range(UpperCamelCase__ ): UpperCamelCase = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : PreTrainedTokenizer , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional[TensorType] = None , ): """simple docstring""" UpperCamelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Generate decoder inputs UpperCamelCase = seq_length if not self.use_past else 1 UpperCamelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = {f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()} UpperCamelCase = dict(**UpperCamelCase__ , **UpperCamelCase__ ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch UpperCamelCase = common_inputs["input_ids"].shape UpperCamelCase = common_inputs["decoder_input_ids"].shape[1] UpperCamelCase = self.num_attention_heads UpperCamelCase = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase = decoder_seq_length + 3 UpperCamelCase = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase = torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(UpperCamelCase__ , UpperCamelCase__ )] , dim=1 ) UpperCamelCase = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase = self.num_layers UpperCamelCase = min(UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = max(UpperCamelCase__ , UpperCamelCase__ ) - min_num_layers UpperCamelCase = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(UpperCamelCase__ ): common_inputs["past_key_values"].append( ( torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ ), ) ) # TODO: test this. UpperCamelCase = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(UpperCamelCase__ , UpperCamelCase__ ): common_inputs["past_key_values"].append((torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) ) return common_inputs def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : PreTrainedTokenizer , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional[TensorType] = None , ): """simple docstring""" UpperCamelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch UpperCamelCase = common_inputs["input_ids"].shape # Not using the same length for past_key_values UpperCamelCase = seqlen + 2 UpperCamelCase = self.num_layers UpperCamelCase = self.num_attention_heads UpperCamelCase = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase = common_inputs["attention_mask"].dtype UpperCamelCase = torch.cat( [common_inputs["""attention_mask"""], torch.ones(UpperCamelCase__ , UpperCamelCase__ , dtype=UpperCamelCase__ )] , dim=1 ) UpperCamelCase = [ (torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) for _ in range(UpperCamelCase__ ) ] return common_inputs def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : PreTrainedTokenizer , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional[TensorType] = None , ): """simple docstring""" UpperCamelCase = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase = tokenizer.num_special_tokens_to_add(UpperCamelCase__ ) UpperCamelCase = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase__ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase = dict(tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ ) ) return common_inputs def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : PreTrainedTokenizer , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional[TensorType] = None , ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = self._generate_dummy_inputs_for_default_and_seqaseq_lm( UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ ) elif self.task == "causal-lm": UpperCamelCase = self._generate_dummy_inputs_for_causal_lm( UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ ) else: UpperCamelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ ) return common_inputs def lowerCamelCase_ ( self : str , lowerCamelCase_ : str , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int] ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = super()._flatten_past_key_values_(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: UpperCamelCase = super(UpperCamelCase__ , self )._flatten_past_key_values_( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
370
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE = {"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = ["""YolosFeatureExtractor"""] _SCREAMING_SNAKE_CASE = ["""YolosImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ """YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST""", """YolosForObjectDetection""", """YolosModel""", """YolosPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
165
0
"""simple docstring""" def __lowerCamelCase ( __UpperCamelCase ) -> str: """simple docstring""" lowerCAmelCase_ : Dict = [0] * len(__UpperCamelCase ) lowerCAmelCase_ : List[Any] = [] lowerCAmelCase_ : List[Any] = [] lowerCAmelCase_ : Optional[int] = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__UpperCamelCase ) ): if indegree[i] == 0: queue.append(__UpperCamelCase ) while queue: lowerCAmelCase_ : List[str] = queue.pop(0 ) cnt += 1 topo.append(__UpperCamelCase ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(__UpperCamelCase ) if cnt != len(__UpperCamelCase ): print("Cycle exists" ) else: print(__UpperCamelCase ) # Adjacency List of Graph lowercase__ = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
241
"""simple docstring""" import os def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" lowerCAmelCase_ : Union[str, Any] = os.path.dirname(os.path.realpath(__UpperCamelCase ) ) lowerCAmelCase_ : List[str] = os.path.join(__UpperCamelCase , "triangle.txt" ) with open(__UpperCamelCase ) as f: lowerCAmelCase_ : Optional[int] = f.readlines() lowerCAmelCase_ : Union[str, Any] = [] for line in triangle: lowerCAmelCase_ : Any = [] for number in line.strip().split(" " ): numbers_from_line.append(int(__UpperCamelCase ) ) a.append(__UpperCamelCase ) for i in range(1 , len(__UpperCamelCase ) ): for j in range(len(a[i] ) ): lowerCAmelCase_ : Optional[Any] = a[i - 1][j] if j != len(a[i - 1] ) else 0 lowerCAmelCase_ : int = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(__UpperCamelCase , __UpperCamelCase ) return max(a[-1] ) if __name__ == "__main__": print(solution())
241
1
"""simple docstring""" import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class UpperCamelCase_ (__A , unittest.TestCase ): __magic_name__ = ProphetNetTokenizer __magic_name__ = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: super().setUp() UpperCAmelCase_ : Optional[int] = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] UpperCAmelCase_ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : Tuple ) -> str: UpperCAmelCase_ : Optional[int] = "UNwant\u00E9d,running" UpperCAmelCase_ : int = "unwanted, running" return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: UpperCAmelCase_ : Optional[Any] = self.tokenizer_class(self.vocab_file ) UpperCAmelCase_ : str = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(lowerCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) , [9, 6, 7, 12, 10, 11] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: UpperCAmelCase_ : Optional[Any] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Any: UpperCAmelCase_ : int = BasicTokenizer(do_lower_case=lowerCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: UpperCAmelCase_ : Any = BasicTokenizer(do_lower_case=lowerCAmelCase_ , strip_accents=lowerCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: UpperCAmelCase_ : Dict = BasicTokenizer(do_lower_case=lowerCAmelCase_ , strip_accents=lowerCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: UpperCAmelCase_ : int = BasicTokenizer(do_lower_case=lowerCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: UpperCAmelCase_ : int = BasicTokenizer(do_lower_case=lowerCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: UpperCAmelCase_ : Any = BasicTokenizer(do_lower_case=lowerCAmelCase_ , strip_accents=lowerCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def _SCREAMING_SNAKE_CASE ( self : str ) -> str: UpperCAmelCase_ : str = BasicTokenizer(do_lower_case=lowerCAmelCase_ , strip_accents=lowerCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: UpperCAmelCase_ : List[Any] = BasicTokenizer(do_lower_case=lowerCAmelCase_ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: UpperCAmelCase_ : int = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] UpperCAmelCase_ : Any = {} for i, token in enumerate(lowerCAmelCase_ ): UpperCAmelCase_ : int = i UpperCAmelCase_ : List[Any] = WordpieceTokenizer(vocab=lowerCAmelCase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: UpperCAmelCase_ : int = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased" ) UpperCAmelCase_ : int = ["A long paragraph for summarization.", "Another paragraph for summarization."] UpperCAmelCase_ : int = [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102] UpperCAmelCase_ : str = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ , return_tensors="pt" ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) UpperCAmelCase_ : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: UpperCAmelCase_ : Optional[Any] = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased" ) UpperCAmelCase_ : Optional[int] = tokenizer.encode("sequence builders" , add_special_tokens=lowerCAmelCase_ ) UpperCAmelCase_ : str = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_ ) UpperCAmelCase_ : Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_ , lowerCAmelCase_ ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
253
"""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 lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''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 UpperCamelCase_ (__A ): __magic_name__ = '''longformer''' def __init__( self : List[str] , lowerCAmelCase_ : Union[List[int], int] = 512 , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : int = 30_522 , lowerCAmelCase_ : int = 768 , lowerCAmelCase_ : int = 12 , lowerCAmelCase_ : int = 12 , lowerCAmelCase_ : int = 3_072 , lowerCAmelCase_ : str = "gelu" , lowerCAmelCase_ : float = 0.1 , lowerCAmelCase_ : float = 0.1 , lowerCAmelCase_ : int = 512 , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : float = 0.0_2 , lowerCAmelCase_ : float = 1e-12 , lowerCAmelCase_ : bool = False , **lowerCAmelCase_ : Optional[int] , ) -> Dict: super().__init__(pad_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = attention_window UpperCAmelCase_ : Dict = sep_token_id UpperCAmelCase_ : Any = bos_token_id UpperCAmelCase_ : Dict = eos_token_id UpperCAmelCase_ : List[str] = vocab_size UpperCAmelCase_ : Any = hidden_size UpperCAmelCase_ : List[Any] = num_hidden_layers UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : int = hidden_act UpperCAmelCase_ : Union[str, Any] = intermediate_size UpperCAmelCase_ : Tuple = hidden_dropout_prob UpperCAmelCase_ : Any = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : List[str] = type_vocab_size UpperCAmelCase_ : Optional[int] = initializer_range UpperCAmelCase_ : Optional[Any] = layer_norm_eps UpperCAmelCase_ : Optional[Any] = onnx_export class UpperCamelCase_ (__A ): def __init__( self : List[Any] , lowerCAmelCase_ : "PretrainedConfig" , lowerCAmelCase_ : str = "default" , lowerCAmelCase_ : "List[PatchingSpec]" = None ) -> Union[str, Any]: super().__init__(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) UpperCAmelCase_ : int = True @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": UpperCAmelCase_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ : Optional[Any] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("global_attention_mask", dynamic_axis), ] ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: UpperCAmelCase_ : Dict = super().outputs if self.task == "default": UpperCAmelCase_ : List[str] = {0: "batch"} return outputs @property def _SCREAMING_SNAKE_CASE ( self : int ) -> float: return 1e-4 @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 14 ) def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase_ : "PreTrainedTokenizerBase" , lowerCAmelCase_ : int = -1 , lowerCAmelCase_ : int = -1 , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : Optional[TensorType] = None , ) -> Mapping[str, Any]: UpperCAmelCase_ : Tuple = super().generate_dummy_inputs( preprocessor=lowerCAmelCase_ , batch_size=lowerCAmelCase_ , seq_length=lowerCAmelCase_ , is_pair=lowerCAmelCase_ , framework=lowerCAmelCase_ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly UpperCAmelCase_ : str = torch.zeros_like(inputs["input_ids"] ) # make every second token global UpperCAmelCase_ : Union[str, Any] = 1 return inputs
253
1
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __snake_case ( unittest.TestCase ): @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' torch.manual_seed(0 ) lowercase : str = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' torch.manual_seed(0 ) lowercase : Any = VQModel( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,latent_channels=3 ,) return model @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' torch.manual_seed(0 ) lowercase : List[str] = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) return CLIPTextModel(snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = self.dummy_uncond_unet lowercase : List[str] = DDIMScheduler() lowercase : List[str] = self.dummy_vq_model lowercase : str = LDMPipeline(unet=snake_case ,vqvae=snake_case ,scheduler=snake_case ) ldm.to(snake_case ) ldm.set_progress_bar_config(disable=snake_case ) lowercase : Any = torch.manual_seed(0 ) lowercase : int = ldm(generator=snake_case ,num_inference_steps=2 ,output_type="""numpy""" ).images lowercase : str = torch.manual_seed(0 ) lowercase : Optional[Any] = ldm(generator=snake_case ,num_inference_steps=2 ,output_type="""numpy""" ,return_dict=snake_case )[0] lowercase : List[str] = image[0, -3:, -3:, -1] lowercase : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowercase : Dict = np.array([0.8_512, 0.818, 0.6_411, 0.6_808, 0.4_465, 0.5_618, 0.46, 0.6_231, 0.5_172] ) lowercase : List[Any] = 1e-2 if torch_device != '''mps''' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class __snake_case ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = LDMPipeline.from_pretrained("""CompVis/ldm-celebahq-256""" ) ldm.to(snake_case ) ldm.set_progress_bar_config(disable=snake_case ) lowercase : Union[str, Any] = torch.manual_seed(0 ) lowercase : str = ldm(generator=snake_case ,num_inference_steps=5 ,output_type="""numpy""" ).images lowercase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowercase : List[Any] = np.array([0.4_399, 0.44_975, 0.46_825, 0.474, 0.4_359, 0.4_581, 0.45_095, 0.4_341, 0.4_447] ) lowercase : Tuple = 1e-2 if torch_device != '''mps''' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
20
'''simple docstring''' from scipy.stats import pearsonr import datasets lowercase : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' lowercase : Optional[Any] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' lowercase : str = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A ( datasets.Metric ): def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Union[str, Any]: """simple docstring""" if return_pvalue: A : Union[str, Any] = pearsonr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )[0] )}
3
0
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _snake_case ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): snake_case__ = LayoutLMTokenizer snake_case__ = LayoutLMTokenizerFast snake_case__ = True snake_case__ = True def lowerCamelCase__ ( self : Optional[int] ): super().setUp() __lowerCamelCase : Optional[Any] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __lowerCamelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def lowerCamelCase__ ( self : Optional[int] , **UpperCAmelCase : Union[str, Any] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase ) def lowerCamelCase__ ( self : List[Any] , UpperCAmelCase : Optional[Any] ): __lowerCamelCase : List[Any] = """UNwant\u00E9d,running""" __lowerCamelCase : Optional[int] = """unwanted, running""" return input_text, output_text def lowerCamelCase__ ( self : Optional[int] ): __lowerCamelCase : Union[str, Any] = self.tokenizer_class(self.vocab_file ) __lowerCamelCase : Optional[Any] = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase ) , [7, 4, 5, 10, 8, 9] ) def lowerCamelCase__ ( self : Any ): pass
350
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''uclanlp/visualbert-vqa''': '''https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json''', '''uclanlp/visualbert-vqa-pre''': '''https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json''', '''uclanlp/visualbert-vqa-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json''' ), '''uclanlp/visualbert-vcr''': '''https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json''', '''uclanlp/visualbert-vcr-pre''': '''https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json''', '''uclanlp/visualbert-vcr-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json''' ), '''uclanlp/visualbert-nlvr2''': '''https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json''', '''uclanlp/visualbert-nlvr2-pre''': '''https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json''', '''uclanlp/visualbert-nlvr2-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json''' ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class _snake_case ( a__ ): snake_case__ = "visual_bert" def __init__( self : int , UpperCAmelCase : Any=30522 , UpperCAmelCase : Tuple=768 , UpperCAmelCase : List[str]=512 , UpperCAmelCase : List[str]=12 , UpperCAmelCase : Tuple=12 , UpperCAmelCase : Any=3072 , UpperCAmelCase : List[str]="gelu" , UpperCAmelCase : Optional[int]=0.1 , UpperCAmelCase : List[str]=0.1 , UpperCAmelCase : Any=512 , UpperCAmelCase : Dict=2 , UpperCAmelCase : int=0.0_2 , UpperCAmelCase : Dict=1E-12 , UpperCAmelCase : List[str]=False , UpperCAmelCase : Tuple=True , UpperCAmelCase : Optional[Any]=1 , UpperCAmelCase : Union[str, Any]=0 , UpperCAmelCase : List[str]=2 , **UpperCAmelCase : str , ): super().__init__(pad_token_id=UpperCAmelCase , bos_token_id=UpperCAmelCase , eos_token_id=UpperCAmelCase , **UpperCAmelCase ) __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : str = max_position_embeddings __lowerCamelCase : str = hidden_size __lowerCamelCase : Union[str, Any] = visual_embedding_dim __lowerCamelCase : Any = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Optional[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : str = attention_probs_dropout_prob __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : List[str] = type_vocab_size __lowerCamelCase : str = layer_norm_eps __lowerCamelCase : List[str] = bypass_transformer __lowerCamelCase : Optional[int] = special_visual_initialize
64
0
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def UpperCamelCase ( _A = "laptop" ): """simple docstring""" __magic_name__ : str = f'https://www.amazon.in/laptop/s?k={product}' __magic_name__ : Optional[int] = { """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""", """Accept-Language""": """en-US, en;q=0.5""", } __magic_name__ : str = BeautifulSoup(requests.get(_A, headers=_A ).text ) # Initialize a Pandas dataframe with the column titles __magic_name__ : Tuple = DataFrame( columns=[ """Product Title""", """Product Link""", """Current Price of the product""", """Product Rating""", """MRP of the product""", """Discount""", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( """div""", attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""}, ), soup.find_all("""div""", attrs={"""class""": """a-row a-size-base a-color-base"""} ), ): try: __magic_name__ : Optional[int] = item.ha.text __magic_name__ : Dict = """https://www.amazon.in/""" + item.ha.a["""href"""] __magic_name__ : str = item.find("""span""", attrs={"""class""": """a-offscreen"""} ).text try: __magic_name__ : str = item.find("""span""", attrs={"""class""": """a-icon-alt"""} ).text except AttributeError: __magic_name__ : str = """Not available""" try: __magic_name__ : Any = ( """₹""" + item.find( """span""", attrs={"""class""": """a-price a-text-price"""} ).text.split("""₹""" )[1] ) except AttributeError: __magic_name__ : str = """""" try: __magic_name__ : str = float( ( ( float(product_mrp.strip("""₹""" ).replace(""",""", """""" ) ) - float(product_price.strip("""₹""" ).replace(""",""", """""" ) ) ) / float(product_mrp.strip("""₹""" ).replace(""",""", """""" ) ) ) * 100 ) except ValueError: __magic_name__ : Optional[Any] = float("""nan""" ) except AttributeError: pass __magic_name__ : Dict = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __magic_name__ : Dict = """ """ __magic_name__ : int = """ """ data_frame.index += 1 return data_frame if __name__ == "__main__": __magic_name__: int = "headphones" get_amazon_product_data(product).to_csv(F"""Amazon Product Data for {product}.csv""")
342
import re def UpperCamelCase ( _A ): """simple docstring""" __magic_name__ : List[Any] = re.compile(R"""^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$""" ) if match := re.search(_A, _A ): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
342
1
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging snake_case : Any = logging.get_logger(__name__) class _snake_case ( _snake_case ): def __init__( self , _lowerCamelCase ): super().__init__() a :str = nn.ModuleList(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = True , ): for i, (image, scale, controlnet) in enumerate(zip(_lowerCamelCase , _lowerCamelCase , self.nets ) ): a :Any = controlnet( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) # merge samples if i == 0: a :str = down_samples, mid_sample else: a :Optional[int] = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(_lowerCamelCase , _lowerCamelCase ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = None , ): a :Optional[Any] = 0 a :Optional[int] = save_directory for controlnet in self.nets: controlnet.save_pretrained( _lowerCamelCase , is_main_process=_lowerCamelCase , save_function=_lowerCamelCase , safe_serialization=_lowerCamelCase , variant=_lowerCamelCase , ) idx += 1 a :Optional[Any] = model_path_to_save + F'''_{idx}''' @classmethod def SCREAMING_SNAKE_CASE__ ( cls , _lowerCamelCase , **_lowerCamelCase ): a :List[str] = 0 a :str = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... a :Any = pretrained_model_path while os.path.isdir(_lowerCamelCase ): a :Dict = ControlNetModel.from_pretrained(_lowerCamelCase , **_lowerCamelCase ) controlnets.append(_lowerCamelCase ) idx += 1 a :List[str] = pretrained_model_path + F'''_{idx}''' logger.info(F'''{len(_lowerCamelCase )} controlnets loaded from {pretrained_model_path}.''' ) if len(_lowerCamelCase ) == 0: raise ValueError( F'''No ControlNets found under {os.path.dirname(_lowerCamelCase )}. Expected at least {pretrained_model_path + '_0'}.''' ) return cls(_lowerCamelCase )
367
def __lowerCamelCase ( UpperCAmelCase_ : int ): """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise TypeError('''Input value must be an \'int\' type''' ) a :Optional[int] = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
281
0
import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor snake_case : List[Any] = logging.getLogger(__name__) snake_case : Tuple = 50 # max width of layer names snake_case : Tuple = 70 # max width of quantizer names def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> str: '''simple docstring''' __magic_name__ : str = parser.add_argument_group("quant_trainer arguments" ) group.add_argument("--wprec" , type=A__ , default=8 , help="weight precision" ) group.add_argument("--aprec" , type=A__ , default=8 , help="activation precision" ) group.add_argument("--quant-per-tensor" , action="store_true" , help="per tensor weight scaling" ) group.add_argument("--quant-disable" , action="store_true" , help="disable all quantizers" ) group.add_argument("--quant-disable-embeddings" , action="store_true" , help="disable all embeddings quantizers" ) group.add_argument("--quant-disable-keyword" , type=A__ , nargs="+" , help="disable quantizers by keyword" ) group.add_argument("--quant-disable-layer-module" , type=A__ , help="disable quantizers by keyword under layer." ) group.add_argument("--quant-enable-layer-module" , type=A__ , help="enable quantizers by keyword under layer" ) group.add_argument("--calibrator" , default="max" , help="which quantization range calibrator to use" ) group.add_argument("--percentile" , default=A__ , type=A__ , help="percentile for PercentileCalibrator" ) group.add_argument("--fuse-qkv" , action="store_true" , help="use the same scale factor for qkv" ) group.add_argument("--clip-gelu" , metavar="N" , type=A__ , help="clip gelu output maximum value to N" ) group.add_argument( "--recalibrate-weights" , action="store_true" , help=( "recalibrate weight amaxes by taking the max of the weights." " amaxes will be computed with the current quantization granularity (axis)." ) , ) def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Any: '''simple docstring''' if args.calibrator == "max": __magic_name__ : Optional[int] = "max" elif args.calibrator == "percentile": if args.percentile is None: raise ValueError("Specify --percentile when using percentile calibrator" ) __magic_name__ : Optional[int] = "histogram" elif args.calibrator == "mse": __magic_name__ : Any = "histogram" else: raise ValueError(F'''Invalid calibrator {args.calibrator}''' ) __magic_name__ : int = QuantDescriptor(num_bits=args.aprec , calib_method=A__ ) __magic_name__ : str = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,)) ) quant_nn.QuantLinear.set_default_quant_desc_input(A__ ) quant_nn.QuantLinear.set_default_quant_desc_weight(A__ ) def lowerCAmelCase_ ( _snake_case : Any , _snake_case : int , _snake_case : int=False , _snake_case : Optional[int]=False ) -> List[str]: '''simple docstring''' logger.info("Configuring Model for Quantization" ) logger.info(F'''using quantization package {pytorch_quantization.__file__}''' ) if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(A__ , ["embeddings"] , which="weight" , _disabled=A__ ) if args.quant_disable: set_quantizer_by_name(A__ , [""] , _disabled=A__ ) if args.quant_disable_keyword: set_quantizer_by_name(A__ , args.quant_disable_keyword , _disabled=A__ ) if args.quant_disable_layer_module: set_quantizer_by_name(A__ , [R"layer.\d+." + args.quant_disable_layer_module] , _disabled=A__ ) if args.quant_enable_layer_module: set_quantizer_by_name(A__ , [R"layer.\d+." + args.quant_enable_layer_module] , _disabled=A__ ) if args.recalibrate_weights: recalibrate_weights(A__ ) if args.fuse_qkv: fuse_qkv(A__ , A__ ) if args.clip_gelu: clip_gelu(A__ , args.clip_gelu ) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(A__ ) def lowerCAmelCase_ ( _snake_case : Tuple ) -> List[Any]: '''simple docstring''' logger.info("Enabling Calibration" ) for name, module in model.named_modules(): if name.endswith("_quantizer" ): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(F'''{name:80}: {module}''' ) def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Union[str, Any] ) -> int: '''simple docstring''' logger.info("Loading calibrated amax" ) for name, module in model.named_modules(): if name.endswith("_quantizer" ): if module._calibrator is not None: if isinstance(module._calibrator , calib.MaxCalibrator ): module.load_calib_amax() else: module.load_calib_amax("percentile" , percentile=args.percentile ) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(A__ ) def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Union[str, Any] ) -> Any: '''simple docstring''' def fusea(_snake_case : Union[str, Any] , _snake_case : Optional[int] , _snake_case : int ): for mod in [qq, qk, qv]: if not hasattr(A__ , "_amax" ): print(" WARNING: NO AMAX BUFFER" ) return __magic_name__ : int = qq._amax.detach().item() __magic_name__ : List[str] = qk._amax.detach().item() __magic_name__ : Optional[Any] = qv._amax.detach().item() __magic_name__ : Tuple = max(A__ , A__ , A__ ) qq._amax.fill_(A__ ) qk._amax.fill_(A__ ) qv._amax.fill_(A__ ) logger.info(F''' q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}''' ) for name, mod in model.named_modules(): if name.endswith(".attention.self" ): logger.info(F'''FUSE_QKV: {name:{name_width}}''' ) fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer ) if args.quant_per_tensor: fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer ) def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : Optional[int] ) -> Any: '''simple docstring''' for name, mod in model.named_modules(): if name.endswith(".output.dense" ) and not name.endswith("attention.output.dense" ): __magic_name__ : Optional[int] = mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=A__ ) __magic_name__ : Optional[Any] = mod._input_quantizer._amax.data.detach().item() logger.info(F'''CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}''' ) def lowerCAmelCase_ ( _snake_case : int ) -> int: '''simple docstring''' for name, mod in model.named_modules(): if hasattr(A__ , "_weight_quantizer" ) and mod._weight_quantizer.axis is not None: __magic_name__ : List[str] = mod.weight.shape[0] __magic_name__ : int = mod._weight_quantizer._amax.detach() __magic_name__ : Dict = torch.ones(A__ , dtype=amax.dtype , device=amax.device ) * amax print(F'''expanding {name} {amax} -> {mod._weight_quantizer._amax}''' ) def lowerCAmelCase_ ( _snake_case : Union[str, Any] ) -> Optional[int]: '''simple docstring''' for name, mod in model.named_modules(): if hasattr(A__ , "_weight_quantizer" ): if not hasattr(mod.weight_quantizer , "_amax" ): print("RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER" ) continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) __magic_name__ : Optional[Any] = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis ) __magic_name__ : Optional[int] = set(range(len(mod.weight.size() ) ) ) - axis_set __magic_name__ : Dict = pytorch_quantization.utils.reduce_amax(mod.weight , axis=A__ , keepdims=A__ ).detach() logger.info(F'''RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}''' ) __magic_name__ : Dict = amax def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Optional[Any]=25 , _snake_case : Dict=180 , _snake_case : int=None ) -> int: '''simple docstring''' if ignore is None: __magic_name__ : Union[str, Any] = [] elif not isinstance(A__ , A__ ): __magic_name__ : Any = [ignore] __magic_name__ : int = 0 for name, mod in model.named_modules(): if not hasattr(A__ , "weight" ): continue __magic_name__ : int = max(A__ , len(A__ ) ) for name, mod in model.named_modules(): __magic_name__ : str = getattr(A__ , "_input_quantizer" , A__ ) __magic_name__ : str = getattr(A__ , "_weight_quantizer" , A__ ) if not hasattr(A__ , "weight" ): continue if type(A__ ) in ignore: continue if [True for s in ignore if type(A__ ) is str and s in name]: continue __magic_name__ : Optional[Any] = F'''Act:{input_q.extra_repr()}''' __magic_name__ : Optional[int] = F'''Wgt:{weight_q.extra_repr()}''' __magic_name__ : int = F'''{name:{name_width}} {act_str} {wgt_str}''' if len(A__ ) <= line_width: logger.info(A__ ) else: logger.info(F'''{name:{name_width}} {act_str}''' ) logger.info(F'''{" ":{name_width}} {wgt_str}''' ) def lowerCAmelCase_ ( _snake_case : List[str] ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Optional[Any] = 0 for name, mod in model.named_modules(): if isinstance(A__ , pytorch_quantization.nn.TensorQuantizer ): print(F'''{name:80} {mod}''' ) count += 1 print(F'''{count} TensorQuantizers found in model''' ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Any , _snake_case : Optional[int] , _snake_case : Tuple , _snake_case : Optional[int] ) -> List[Any]: '''simple docstring''' __magic_name__ : Optional[int] = getattr(A__ , A__ , A__ ) if quantizer_mod is not None: assert hasattr(A__ , A__ ) setattr(A__ , A__ , A__ ) else: logger.warning(F'''{name} has no {quantizer}''' ) def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : Tuple , _snake_case : Tuple="both" , **_snake_case : Any ) -> List[str]: '''simple docstring''' __magic_name__ : Tuple = F'''Warning: changing {which} quantizers of {name:{qname_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' if which in ["input", "both"]: set_quantizer(A__ , A__ , "_input_quantizer" , A__ , A__ ) if which in ["weight", "both"]: set_quantizer(A__ , A__ , "_weight_quantizer" , A__ , A__ ) logger.info(A__ ) def lowerCAmelCase_ ( _snake_case : Any , _snake_case : List[Any] , **_snake_case : List[Any] ) -> List[Any]: '''simple docstring''' for name, mod in model.named_modules(): if hasattr(A__ , "_input_quantizer" ) or hasattr(A__ , "_weight_quantizer" ): for n in names: if re.search(A__ , A__ ): set_quantizers(A__ , A__ , **A__ ) elif name.endswith("_quantizer" ): for n in names: if re.search(A__ , A__ ): __magic_name__ : int = F'''Warning: changing {name:{name_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' setattr(A__ , A__ , A__ ) logger.info(A__ )
281
'''simple docstring''' import colorsys from PIL import Image # type: ignore def _A ( A__ , A__ , A__ ): """simple docstring""" __lowercase = x __lowercase = y for step in range(A__ ): # noqa: B007 __lowercase = a * a - b * b + x __lowercase = 2 * a * b + y __lowercase = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _A ( A__ ): """simple docstring""" if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def _A ( A__ ): """simple docstring""" if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(A__ , 1 , 1 ) ) def _A ( A__ = 800 , A__ = 600 , A__ = -0.6 , A__ = 0 , A__ = 3.2 , A__ = 50 , A__ = True , ): """simple docstring""" __lowercase = Image.new('''RGB''' , (image_width, image_height) ) __lowercase = img.load() # loop through the image-coordinates for image_x in range(A__ ): for image_y in range(A__ ): # determine the figure-coordinates based on the image-coordinates __lowercase = figure_width / image_width * image_height __lowercase = figure_center_x + (image_x / image_width - 0.5) * figure_width __lowercase = figure_center_y + (image_y / image_height - 0.5) * figure_height __lowercase = get_distance(A__ , A__ , A__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __lowercase = get_color_coded_rgb(A__ ) else: __lowercase = get_black_and_white_rgb(A__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCAmelCase__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
104
0
'''simple docstring''' import math from datetime import datetime, timedelta def lowerCamelCase__ ( __lowerCamelCase : int ): '''simple docstring''' _UpperCAmelCase : Optional[Any] =year % 1_9 _UpperCAmelCase : Union[str, Any] =year % 4 _UpperCAmelCase : Optional[int] =year % 7 _UpperCAmelCase : str =math.floor(year / 1_0_0 ) _UpperCAmelCase : Union[str, Any] =math.floor((1_3 + 8 * leap_day_inhibits) / 2_5 ) _UpperCAmelCase : Union[str, Any] =leap_day_inhibits / 4 _UpperCAmelCase : int =( 1_5 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 3_0 _UpperCAmelCase : Any =(4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 _UpperCAmelCase : Tuple =(1_9 * metonic_cycle + secular_moon_shift) % 3_0 # PHM -> Paschal Full Moon _UpperCAmelCase : Tuple =( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 2_9 and days_from_phm_to_sunday == 6: return datetime(__lowerCamelCase , 4 , 1_9 ) elif days_to_add == 2_8 and days_from_phm_to_sunday == 6: return datetime(__lowerCamelCase , 4 , 1_8 ) else: return datetime(__lowerCamelCase , 3 , 2_2 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): lowercase ='will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
242
'''simple docstring''' from typing import Any def lowerCamelCase__ ( __lowerCamelCase : list , __lowerCamelCase : list , __lowerCamelCase : dict , __lowerCamelCase : dict , __lowerCamelCase : dict , ): '''simple docstring''' _validation( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) # Creates data structures and fill initial step _UpperCAmelCase : dict ={} _UpperCAmelCase : dict ={} for state in states_space: _UpperCAmelCase : int =observations_space[0] _UpperCAmelCase : int =( initial_probabilities[state] * emission_probabilities[state][observation] ) _UpperCAmelCase : int =None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1 , len(__lowerCamelCase ) ): _UpperCAmelCase : List[Any] =observations_space[o] _UpperCAmelCase : Optional[int] =observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function _UpperCAmelCase : List[str] ='' _UpperCAmelCase : Dict =-1 for k_state in states_space: _UpperCAmelCase : List[str] =( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: _UpperCAmelCase : int =probability _UpperCAmelCase : List[Any] =k_state # Update probabilities and pointers dicts _UpperCAmelCase : str =( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) _UpperCAmelCase : List[Any] =arg_max # The final observation _UpperCAmelCase : int =observations_space[len(__lowerCamelCase ) - 1] # argmax for given final observation _UpperCAmelCase : Any ='' _UpperCAmelCase : Union[str, Any] =-1 for k_state in states_space: _UpperCAmelCase : Optional[int] =probabilities[(k_state, final_observation)] if probability > max_probability: _UpperCAmelCase : Union[str, Any] =probability _UpperCAmelCase : int =k_state _UpperCAmelCase : int =arg_max # Process pointers backwards _UpperCAmelCase : List[str] =last_state _UpperCAmelCase : Optional[int] =[] for o in range(len(__lowerCamelCase ) - 1 , -1 , -1 ): result.append(__lowerCamelCase ) _UpperCAmelCase : Optional[Any] =pointers[previous, observations_space[o]] result.reverse() return result def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Any , ): '''simple docstring''' _validate_not_empty( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) _validate_lists(__lowerCamelCase , __lowerCamelCase ) _validate_dicts( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Any , ): '''simple docstring''' if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError('There\'s an empty parameter' ) def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : Any ): '''simple docstring''' _validate_list(__lowerCamelCase , 'observations_space' ) _validate_list(__lowerCamelCase , 'states_space' ) def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : str ): '''simple docstring''' if not isinstance(_object , __lowerCamelCase ): _UpperCAmelCase : Any =f"{var_name} must be a list" raise ValueError(__lowerCamelCase ) else: for x in _object: if not isinstance(__lowerCamelCase , __lowerCamelCase ): _UpperCAmelCase : Optional[int] =f"{var_name} must be a list of strings" raise ValueError(__lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Any , ): '''simple docstring''' _validate_dict(__lowerCamelCase , 'initial_probabilities' , __lowerCamelCase ) _validate_nested_dict(__lowerCamelCase , 'transition_probabilities' ) _validate_nested_dict(__lowerCamelCase , 'emission_probabilities' ) def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : str ): '''simple docstring''' _validate_dict(_object , __lowerCamelCase , __lowerCamelCase ) for x in _object.values(): _validate_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : str , __lowerCamelCase : type , __lowerCamelCase : bool = False ): '''simple docstring''' if not isinstance(_object , __lowerCamelCase ): _UpperCAmelCase : List[str] =f"{var_name} must be a dict" raise ValueError(__lowerCamelCase ) if not all(isinstance(__lowerCamelCase , __lowerCamelCase ) for x in _object ): _UpperCAmelCase : str =f"{var_name} all keys must be strings" raise ValueError(__lowerCamelCase ) if not all(isinstance(__lowerCamelCase , __lowerCamelCase ) for x in _object.values() ): _UpperCAmelCase : int ='nested dictionary ' if nested else '' _UpperCAmelCase : Optional[int] =f"{var_name} {nested_text}all values must be {value_type.__name__}" raise ValueError(__lowerCamelCase ) if __name__ == "__main__": from doctest import testmod testmod()
242
1
from __future__ import annotations from random import choice def _a ( SCREAMING_SNAKE_CASE : Optional[Any] ) -> Optional[Any]: """simple docstring""" return choice(_SCREAMING_SNAKE_CASE ) def _a ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ) -> int: """simple docstring""" __lowerCAmelCase: List[str] = random_pivot(_SCREAMING_SNAKE_CASE ) # partition based on pivot # linear time __lowerCAmelCase: Optional[int] = [e for e in lst if e < pivot] __lowerCAmelCase: int = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(_SCREAMING_SNAKE_CASE ) == k - 1: return pivot # pivot is in elements bigger than k elif len(_SCREAMING_SNAKE_CASE ) < k - 1: return kth_number(_SCREAMING_SNAKE_CASE , k - len(_SCREAMING_SNAKE_CASE ) - 1 ) # pivot is in elements smaller than k else: return kth_number(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
322
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin lowercase__ = get_tests_dir('fixtures/test_sentencepiece.model') lowercase__ = get_tests_dir('fixtures/test_sentencepiece_bpe.model') lowercase__ = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class __snake_case ( __lowerCAmelCase , unittest.TestCase ): a__ = CamembertTokenizer a__ = CamembertTokenizerFast a__ = True a__ = True def lowerCamelCase_ ( self) -> Union[str, Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing a__: Tuple = CamembertTokenizer(lowercase) tokenizer.save_pretrained(self.tmpdirname) def lowerCamelCase_ ( self) -> List[str]: '''simple docstring''' a__: Optional[Any] = '<pad>' a__: List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase) , lowercase) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase) , lowercase) def lowerCamelCase_ ( self) -> Any: '''simple docstring''' a__: str = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '<s>NOTUSED') self.assertEqual(vocab_keys[1] , '<pad>') self.assertEqual(vocab_keys[-1] , '<mask>') self.assertEqual(len(lowercase) , 10_04) def lowerCamelCase_ ( self) -> Any: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 10_05) def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' a__: Optional[Any] = CamembertTokenizer(lowercase) tokenizer.save_pretrained(self.tmpdirname) a__: List[Any] = CamembertTokenizerFast.from_pretrained(self.tmpdirname) a__: Dict = 'I was born in 92000, and this is falsé.' a__: Optional[int] = tokenizer.encode(lowercase) a__: Any = rust_tokenizer.encode(lowercase) self.assertListEqual(lowercase , lowercase) a__: Optional[Any] = tokenizer.encode(lowercase , add_special_tokens=lowercase) a__: str = rust_tokenizer.encode(lowercase , add_special_tokens=lowercase) self.assertListEqual(lowercase , lowercase) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) a__: Tuple = tokenizer.convert_ids_to_tokens(lowercase) a__: Tuple = rust_tokenizer.tokenize(lowercase) self.assertListEqual(lowercase , lowercase) def lowerCamelCase_ ( self) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__: Dict = self.get_tokenizer() a__: str = self.get_rust_tokenizer() a__: int = 'I was born in 92000, and this is falsé.' a__: Optional[Any] = tokenizer.tokenize(lowercase) a__: List[Any] = rust_tokenizer.tokenize(lowercase) self.assertListEqual(lowercase , lowercase) a__: str = tokenizer.encode(lowercase , add_special_tokens=lowercase) a__: str = rust_tokenizer.encode(lowercase , add_special_tokens=lowercase) self.assertListEqual(lowercase , lowercase) a__: Tuple = self.get_rust_tokenizer() a__: Union[str, Any] = tokenizer.encode(lowercase) a__: List[Any] = rust_tokenizer.encode(lowercase) self.assertListEqual(lowercase , lowercase) @slow def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' a__: Union[str, Any] = {'input_ids': [[5, 54, 71_96, 2_97, 30, 23, 7_76, 18, 11, 32_15, 37_05, 82_52, 22, 31_64, 11_81, 21_16, 29, 16, 8_13, 25, 7_91, 33_14, 20, 34_46, 38, 2_75_75, 1_20, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_68, 17, 11, 90_88, 20, 15_17, 8, 2_28_04, 1_88_18, 10, 38, 6_29, 6_07, 6_07, 1_42, 19, 71_96, 8_67, 56, 1_03_26, 24, 22_67, 20, 4_16, 50_72, 1_56_12, 2_33, 7_34, 7, 23_99, 27, 16, 30_15, 16_49, 7, 24, 20, 43_38, 23_99, 27, 13, 34_00, 14, 13, 61_89, 8, 9_30, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. a__: int = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=lowercase , )
290
0
'''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 lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class A__ ( A__ ): A__ = 'yolos' def __init__( self : str , _a : Any=768 , _a : Tuple=12 , _a : List[str]=12 , _a : Dict=3072 , _a : List[Any]="gelu" , _a : Optional[int]=0.0 , _a : Dict=0.0 , _a : Optional[Any]=0.02 , _a : Dict=1e-12 , _a : str=[512, 864] , _a : Dict=16 , _a : Tuple=3 , _a : Union[str, Any]=True , _a : Any=100 , _a : List[str]=True , _a : List[Any]=False , _a : Dict=1 , _a : List[str]=5 , _a : str=2 , _a : int=5 , _a : Optional[Any]=2 , _a : str=0.1 , **_a : List[Any] , ) -> Tuple: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =intermediate_size _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =hidden_dropout_prob _SCREAMING_SNAKE_CASE =attention_probs_dropout_prob _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =patch_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =qkv_bias _SCREAMING_SNAKE_CASE =num_detection_tokens _SCREAMING_SNAKE_CASE =use_mid_position_embeddings _SCREAMING_SNAKE_CASE =auxiliary_loss # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient class A__ ( A__ ): A__ = version.parse('1.11' ) @property def A ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def A ( self : int ) -> float: '''simple docstring''' return 1e-4 @property def A ( self : Tuple ) -> int: '''simple docstring''' return 12
114
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : List[str] = {"configuration_ibert": ["IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "IBertConfig", "IBertOnnxConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "IBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "IBertForMaskedLM", "IBertForMultipleChoice", "IBertForQuestionAnswering", "IBertForSequenceClassification", "IBertForTokenClassification", "IBertModel", "IBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys lowerCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
114
1
import unittest import numpy as np def _a ( SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : np.ndarray | None = None , ) -> np.ndarray: """simple docstring""" __lowerCAmelCase: Any = np.shape(_snake_case ) __lowerCAmelCase: List[str] = np.shape(_snake_case ) __lowerCAmelCase: Dict = np.shape(_snake_case ) if shape_a[0] != shape_b[0]: __lowerCAmelCase: List[Any] = ( "Expected the same number of rows for A and B. " f'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(_snake_case ) if shape_b[1] != shape_c[1]: __lowerCAmelCase: Any = ( "Expected the same number of columns for B and C. " f'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(_snake_case ) __lowerCAmelCase: str = pseudo_inv if a_inv is None: try: __lowerCAmelCase: int = np.linalg.inv(_snake_case ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class A_ ( unittest.TestCase ): def UpperCAmelCase ( self : Tuple ) -> Union[str, Any]: __lowerCAmelCase: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __lowerCAmelCase: Dict = np.array([[0, 3], [3, 0], [2, 3]] ) __lowerCAmelCase: List[Any] = np.array([[2, 1], [6, 3]] ) __lowerCAmelCase: Dict = schur_complement(_a , _a , _a ) __lowerCAmelCase: int = np.block([[a, b], [b.T, c]] ) __lowerCAmelCase: Dict = np.linalg.det(_a ) __lowerCAmelCase: str = np.linalg.det(_a ) __lowerCAmelCase: Dict = np.linalg.det(_a ) self.assertAlmostEqual(_a , det_a * det_s ) def UpperCAmelCase ( self : Tuple ) -> Optional[int]: __lowerCAmelCase: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __lowerCAmelCase: str = np.array([[0, 3], [3, 0], [2, 3]] ) __lowerCAmelCase: Union[str, Any] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_a ): schur_complement(_a , _a , _a ) def UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]: __lowerCAmelCase: Dict = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __lowerCAmelCase: Optional[Any] = np.array([[0, 3], [3, 0], [2, 3]] ) __lowerCAmelCase: List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_a ): schur_complement(_a , _a , _a ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
322
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin snake_case : str = "▁" snake_case : List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = BigBirdTokenizer UpperCamelCase__ = BigBirdTokenizerFast UpperCamelCase__ = True UpperCamelCase__ = True def SCREAMING_SNAKE_CASE ( self ): super().setUp() __magic_name__ : Optional[Any] = self.tokenizer_class(_a , keep_accents=_a ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = "<s>" __magic_name__ : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "[MASK]" ) self.assertEqual(len(_a ) , 1_004 ) def SCREAMING_SNAKE_CASE ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def SCREAMING_SNAKE_CASE ( self ): if not self.test_rust_tokenizer: return __magic_name__ : Dict = self.get_tokenizer() __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Any = "I was born in 92000, and this is falsé." __magic_name__ : Dict = tokenizer.tokenize(_a ) __magic_name__ : Any = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) __magic_name__ : List[Any] = tokenizer.encode(_a , add_special_tokens=_a ) __magic_name__ : List[str] = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Dict = tokenizer.encode(_a ) __magic_name__ : Optional[int] = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = BigBirdTokenizer(_a , keep_accents=_a ) __magic_name__ : str = tokenizer.tokenize("This is a test" ) self.assertListEqual(_a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [285, 46, 10, 170, 382] , ) __magic_name__ : Dict = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _a , [ 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", "é", ".", ] , ) __magic_name__ : Union[str, Any] = tokenizer.convert_tokens_to_ids(_a ) self.assertListEqual( _a , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __magic_name__ : int = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE ( self ): return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = "Hello World!" __magic_name__ : Dict = [65, 18_536, 2_260, 101, 66] self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = ( "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" ) # fmt: off __magic_name__ : List[str] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231 # fmt: on self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @require_torch @slow def SCREAMING_SNAKE_CASE ( self ): import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence __magic_name__ : Optional[Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] __magic_name__ : List[Any] = " ".join(_a ) __magic_name__ : Any = self.big_tokenizer.encode_plus(_a , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : Union[str, Any] = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : List[str] = BigBirdConfig(attention_type="original_full" ) __magic_name__ : Optional[int] = BigBirdModel(_a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_a ) model(**_a ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) __magic_name__ : int = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def SCREAMING_SNAKE_CASE ( self ): # fmt: off __magic_name__ : Optional[Any] = {"input_ids": [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name="google/bigbird-roberta-base" , revision="215c99f1600e06f83acce68422f2035b2b5c3510" , )
281
0
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib snake_case : List[Any] = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } snake_case : int = logging.WARNING def __lowercase ( ): a__ = os.getenv('DATASETS_VERBOSITY' , __lowerCAmelCase ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option DATASETS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def __lowercase ( ): return __name__.split('.' )[0] def __lowercase ( ): return logging.getLogger(_get_library_name() ) def __lowercase ( ): # Apply our default configuration to the library root logger. a__ = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def __lowercase ( ): a__ = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def __lowercase ( __lowerCAmelCase : Optional[str] = None ): if name is None: a__ = _get_library_name() return logging.getLogger(__lowerCAmelCase ) def __lowercase ( ): return _get_library_root_logger().getEffectiveLevel() def __lowercase ( __lowerCAmelCase : int ): _get_library_root_logger().setLevel(__lowerCAmelCase ) def __lowercase ( ): return set_verbosity(__lowerCAmelCase ) def __lowercase ( ): return set_verbosity(__lowerCAmelCase ) def __lowercase ( ): return set_verbosity(__lowerCAmelCase ) def __lowercase ( ): return set_verbosity(__lowerCAmelCase ) def __lowercase ( ): a__ = False def __lowercase ( ): a__ = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class snake_case_ : def __init__( self :Any ,*__snake_case :Optional[int] ,**__snake_case :Optional[int] ) -> List[str]: # pylint: disable=unused-argument a__ = args[0] if args else None def __iter__( self :Tuple ) -> List[str]: return iter(self._iterator ) def __getattr__( self :Any ,__snake_case :str ) -> Union[str, Any]: def empty_fn(*__snake_case :Union[str, Any] ,**__snake_case :int ): # pylint: disable=unused-argument return return empty_fn def __enter__( self :Any ) -> List[Any]: return self def __exit__( self :Any ,__snake_case :List[str] ,__snake_case :Any ,__snake_case :Tuple ) -> Any: return snake_case : Union[str, Any] = True class snake_case_ : def __call__( self :Union[str, Any] ,*__snake_case :Optional[Any] ,__snake_case :List[Any]=False ,**__snake_case :List[Any] ) -> Any: if _tqdm_active and not disable: return tqdm_lib.tqdm(*__snake_case ,**__snake_case ) else: return EmptyTqdm(*__snake_case ,**__snake_case ) def lowerCamelCase__( self :Optional[int] ,*__snake_case :Union[str, Any] ,**__snake_case :Any ) -> Any: a__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*__snake_case ,**__snake_case ) def lowerCamelCase__( self :Optional[int] ) -> Tuple: if _tqdm_active: return tqdm_lib.tqdm.get_lock() snake_case : List[str] = _tqdm_cls() def __lowercase ( ): global _tqdm_active return bool(_tqdm_active ) def __lowercase ( ): global _tqdm_active a__ = True def __lowercase ( ): global _tqdm_active a__ = False
109
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Tuple = logging.get_logger(__name__) snake_case : List[Any] = { '''snap-research/efficientformer-l1-300''': ( '''https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json''' ), } class snake_case_ (lowerCamelCase_ ): UpperCAmelCase__ : int = '''efficientformer''' def __init__( self :List[str] ,__snake_case :List[int] = [3, 2, 6, 4] ,__snake_case :List[int] = [48, 96, 2_24, 4_48] ,__snake_case :List[bool] = [True, True, True, True] ,__snake_case :int = 4_48 ,__snake_case :int = 32 ,__snake_case :int = 4 ,__snake_case :int = 7 ,__snake_case :int = 5 ,__snake_case :int = 8 ,__snake_case :int = 4 ,__snake_case :float = 0.0 ,__snake_case :int = 16 ,__snake_case :int = 3 ,__snake_case :int = 3 ,__snake_case :int = 3 ,__snake_case :int = 2 ,__snake_case :int = 1 ,__snake_case :float = 0.0 ,__snake_case :int = 1 ,__snake_case :bool = True ,__snake_case :bool = True ,__snake_case :float = 1E-5 ,__snake_case :str = "gelu" ,__snake_case :float = 0.02 ,__snake_case :float = 1E-12 ,__snake_case :int = 2_24 ,__snake_case :float = 1E-05 ,**__snake_case :Dict ,) -> None: super().__init__(**__snake_case ) a__ = hidden_act a__ = hidden_dropout_prob a__ = hidden_sizes a__ = num_hidden_layers a__ = num_attention_heads a__ = initializer_range a__ = layer_norm_eps a__ = patch_size a__ = num_channels a__ = depths a__ = mlp_expansion_ratio a__ = downsamples a__ = dim a__ = key_dim a__ = attention_ratio a__ = resolution a__ = pool_size a__ = downsample_patch_size a__ = downsample_stride a__ = downsample_pad a__ = drop_path_rate a__ = num_metaad_blocks a__ = distillation a__ = use_layer_scale a__ = layer_scale_init_value a__ = image_size a__ = batch_norm_eps
109
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : Optional[Any] = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class lowerCAmelCase ( __a ): '''simple docstring''' _A : str = '''sew''' def __init__( self : Tuple , __a : List[str]=32 , __a : Union[str, Any]=768 , __a : Optional[Any]=12 , __a : Optional[int]=12 , __a : List[Any]=3072 , __a : str=2 , __a : Optional[int]="gelu" , __a : List[str]=0.1 , __a : Dict=0.1 , __a : Optional[int]=0.1 , __a : Dict=0.0 , __a : str=0.1 , __a : List[Any]=0.1 , __a : List[Any]=0.02 , __a : Dict=1E-5 , __a : str="group" , __a : Optional[Any]="gelu" , __a : Optional[Any]=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , __a : List[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , __a : int=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , __a : Any=False , __a : Tuple=128 , __a : List[Any]=16 , __a : Union[str, Any]=True , __a : Optional[Any]=0.05 , __a : Any=10 , __a : List[Any]=2 , __a : int=0.0 , __a : Dict=10 , __a : List[str]=0 , __a : str="mean" , __a : Optional[int]=False , __a : Tuple=False , __a : str=256 , __a : Optional[int]=0 , __a : Any=1 , __a : Any=2 , **__a : List[Any] , ) -> Optional[Any]: """simple docstring""" super().__init__(**__a , pad_token_id=__a , bos_token_id=__a , eos_token_id=__a ) __lowercase : str = hidden_size __lowercase : Dict = feat_extract_norm __lowercase : Tuple = feat_extract_activation __lowercase : Optional[Any] = list(__a ) __lowercase : Optional[int] = list(__a ) __lowercase : str = list(__a ) __lowercase : int = conv_bias __lowercase : Optional[Any] = num_conv_pos_embeddings __lowercase : Optional[Any] = num_conv_pos_embedding_groups __lowercase : List[Any] = len(self.conv_dim ) __lowercase : Optional[int] = num_hidden_layers __lowercase : List[Any] = intermediate_size __lowercase : Tuple = squeeze_factor __lowercase : Any = hidden_act __lowercase : Dict = num_attention_heads __lowercase : List[str] = hidden_dropout __lowercase : Dict = attention_dropout __lowercase : List[str] = activation_dropout __lowercase : Optional[int] = feat_proj_dropout __lowercase : Any = final_dropout __lowercase : Tuple = layerdrop __lowercase : Optional[int] = layer_norm_eps __lowercase : Tuple = initializer_range __lowercase : Any = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F"but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)" F"= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __lowercase : List[Any] = apply_spec_augment __lowercase : int = mask_time_prob __lowercase : Any = mask_time_length __lowercase : str = mask_time_min_masks __lowercase : str = mask_feature_prob __lowercase : Tuple = mask_feature_length __lowercase : Optional[Any] = mask_feature_min_masks # ctc loss __lowercase : str = ctc_loss_reduction __lowercase : Dict = ctc_zero_infinity # sequence classification __lowercase : Dict = use_weighted_layer_sum __lowercase : Optional[int] = classifier_proj_size @property def lowerCAmelCase ( self : Tuple ) -> Dict: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
233
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase : int = '''▁''' lowerCamelCase : Optional[int] = {'''vocab_file''': '''spiece.model'''} lowerCamelCase : str = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } lowerCamelCase : str = { '''google/pegasus-xsum''': 5_12, } lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase ( __a ): '''simple docstring''' _A : Tuple = VOCAB_FILES_NAMES _A : Tuple = VOCAB_FILES_NAMES _A : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _A : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , __a : int , __a : Any="<pad>" , __a : Optional[int]="</s>" , __a : Union[str, Any]="<unk>" , __a : Optional[int]="<mask_2>" , __a : Optional[int]="<mask_1>" , __a : Dict=None , __a : List[str]=103 , __a : Optional[Dict[str, Any]] = None , **__a : List[Any] , ) -> None: """simple docstring""" __lowercase : Tuple = offset if additional_special_tokens is not None: if not isinstance(__a , __a ): raise TypeError( F"additional_special_tokens should be of type {type(__a )}, but is" F" {type(__a )}" ) __lowercase : Dict = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F"<unk_{i}>" for i in range(len(__a ) , self.offset - 1 ) ] if len(set(__a ) ) != len(__a ): raise ValueError( """Please make sure that the provided additional_special_tokens do not contain an incorrectly""" F" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}." ) __lowercase : Optional[Any] = additional_special_tokens_extended else: __lowercase : int = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"<unk_{i}>" for i in range(2 , self.offset )] __lowercase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__a , unk_token=__a , mask_token=__a , pad_token=__a , mask_token_sent=__a , offset=__a , additional_special_tokens=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) __lowercase : Optional[Any] = mask_token_sent __lowercase : Dict = vocab_file __lowercase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__a ) # add special tokens to encoder dict __lowercase : Dict[int, str] = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) __lowercase : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def lowerCAmelCase ( self : Dict ) -> int: """simple docstring""" return len(self.sp_model ) + self.offset def lowerCAmelCase ( self : int ) -> Dict[str, int]: """simple docstring""" __lowercase : Any = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[str] ) -> List[str]: """simple docstring""" __lowercase : Union[str, Any] = self.__dict__.copy() __lowercase : Optional[Any] = None return state def __setstate__( self : Tuple , __a : Any ) -> Tuple: """simple docstring""" __lowercase : List[str] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __lowercase : List[str] = {} __lowercase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Dict , __a : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__a , out_type=__a ) def lowerCAmelCase ( self : List[str] , __a : str ) -> int: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] __lowercase : Union[str, Any] = self.sp_model.piece_to_id(__a ) return sp_id + self.offset def lowerCAmelCase ( self : Dict , __a : int ) -> str: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: __lowercase : List[Any] = self.sp_model.IdToPiece(index - self.offset ) return token def lowerCAmelCase ( self : Union[str, Any] , __a : int ) -> Dict: """simple docstring""" __lowercase : Optional[int] = [] __lowercase : Tuple = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__a ) + token __lowercase : str = [] else: current_sub_tokens.append(__a ) out_string += self.sp_model.decode(__a ) return out_string.strip() def lowerCAmelCase ( self : int , __a : Optional[Any]=False ) -> int: """simple docstring""" return 1 def lowerCAmelCase ( self : Optional[int] , __a : List[str] ) -> Optional[Any]: """simple docstring""" __lowercase : List[Any] = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def lowerCAmelCase ( self : Union[str, Any] , __a : List , __a : Optional[List] = None , __a : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return self._special_token_mask(__a ) elif token_ids_a is None: return self._special_token_mask(__a ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def lowerCAmelCase ( self : Optional[int] , __a : Dict , __a : Tuple=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowerCAmelCase ( self : Tuple , __a : str , __a : 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 __lowercase : Optional[int] = os.path.join( __a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) 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: __lowercase : Any = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,)
233
1
# using dfs for finding eulerian path traversal def a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tuple=None ): """simple docstring""" UpperCamelCase : Union[str, Any] = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: UpperCamelCase : Dict = True, True UpperCamelCase : Union[str, Any] = dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return path def a ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict ): """simple docstring""" UpperCamelCase : Union[str, Any] = 0 UpperCamelCase : Optional[int] = -1 for i in range(SCREAMING_SNAKE_CASE_ ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 UpperCamelCase : Any = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" UpperCamelCase : List[str] = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] UpperCamelCase : Union[str, Any] = check_circuit_or_path(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if check == 3: print('''graph is not Eulerian''' ) print('''no path''' ) return UpperCamelCase : Optional[int] = 1 if check == 2: UpperCamelCase : Tuple = odd_node print('''graph has a Euler path''' ) if check == 1: print('''graph has a Euler cycle''' ) UpperCamelCase : List[Any] = dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) print(SCREAMING_SNAKE_CASE_ ) def a ( ): """simple docstring""" UpperCamelCase : Optional[Any] = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} UpperCamelCase : Optional[int] = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} UpperCamelCase : Dict = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} UpperCamelCase : str = {1: [2, 3], 2: [1, 3], 3: [1, 2]} UpperCamelCase : Any = { 1: [], 2: [] # all degree is zero } UpperCamelCase : Any = 1_0 check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
371
def a ( SCREAMING_SNAKE_CASE_ : int = 5_0 ): """simple docstring""" UpperCamelCase : List[str] = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f'''{solution() = }''')
315
0
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( lowercase_ ): '''simple docstring''' __UpperCAmelCase : Any = ['input_ids', 'attention_mask'] def __init__( self , _a="</s>" , _a="<unk>" , _a="<pad>" , _a=125 , _a=None , **_a , ): if extra_ids > 0 and additional_special_tokens is None: __a = [f'''<extra_id_{i}>''' for i in range(__UpperCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __a = len(set(filter(lambda _a : bool('''extra_id''' in str(__UpperCamelCase ) ) , __UpperCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the''' ''' extra_ids tokens''' ) __a = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else pad_token __a = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else eos_token __a = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else unk_token super().__init__( eos_token=__UpperCamelCase , unk_token=__UpperCamelCase , pad_token=__UpperCamelCase , extra_ids=__UpperCamelCase , additional_special_tokens=__UpperCamelCase , **__UpperCamelCase , ) __a = extra_ids __a = 2**8 # utf is 8 bits # define special tokens dict __a = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __a = len(self.special_tokens_encoder ) __a = len(__UpperCamelCase ) for i, token in enumerate(__UpperCamelCase ): __a = self.vocab_size + i - n __a = {v: k for k, v in self.special_tokens_encoder.items()} @property def __UpperCAmelCase ( self ): return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def __UpperCAmelCase ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCamelCase , token_ids_a=__UpperCamelCase , already_has_special_tokens=__UpperCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__UpperCamelCase )) + [1] return ([0] * len(__UpperCamelCase )) + [1] + ([0] * len(__UpperCamelCase )) + [1] def __UpperCAmelCase ( self , _a ): if len(__UpperCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def __UpperCAmelCase ( self , _a , _a = None ): __a = self._add_eos_if_not_present(__UpperCamelCase ) if token_ids_a is None: return token_ids_a else: __a = self._add_eos_if_not_present(__UpperCamelCase ) return token_ids_a + token_ids_a def __UpperCAmelCase ( self , _a ): __a = [chr(__UpperCamelCase ) for i in text.encode('''utf-8''' )] return tokens def __UpperCAmelCase ( self , _a ): if token in self.special_tokens_encoder: __a = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __a = self.added_tokens_encoder[token] elif len(__UpperCamelCase ) != 1: __a = self.unk_token_id else: __a = ord(__UpperCamelCase ) + self._num_special_tokens return token_id def __UpperCAmelCase ( self , _a ): if index in self.special_tokens_decoder: __a = self.special_tokens_decoder[index] else: __a = chr(index - self._num_special_tokens ) return token def __UpperCAmelCase ( self , _a ): __a = B'' for token in tokens: if token in self.special_tokens_decoder: __a = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.added_tokens_decoder: __a = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.special_tokens_encoder: __a = token.encode('''utf-8''' ) elif token in self.added_tokens_encoder: __a = token.encode('''utf-8''' ) else: __a = bytes([ord(__UpperCamelCase )] ) bstring += tok_string __a = bstring.decode('''utf-8''' , errors='''ignore''' ) return string def __UpperCAmelCase ( self , _a , _a = None ): return ()
45
"""simple docstring""" from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def lowercase__( __SCREAMING_SNAKE_CASE : Optional[int] ): return {key.lstrip('-' ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def lowercase__( ): lowercase_ : Any = ArgumentParser( 'HuggingFace Datasets CLI tool' , usage='datasets-cli <command> [<args>]' , allow_abbrev=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = parser.add_subparsers(help='datasets-cli command helpers' ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) EnvironmentCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) TestCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) RunBeamCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) DummyDataCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) # Parse args lowercase_ , lowercase_ : Dict = parser.parse_known_args() if not hasattr(__SCREAMING_SNAKE_CASE , 'func' ): parser.print_help() exit(1 ) lowercase_ : int = parse_unknown_args(__SCREAMING_SNAKE_CASE ) # Run lowercase_ : List[Any] = args.func(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
213
0
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 : List[str] , _A : Optional[int] , _A : Union[str, Any]=7 , _A : Dict=3 , _A : Dict=30 , _A : List[str]=400 , _A : int=True , _A : Any=None , _A : int=True , _A : Optional[Any]=1 / 255 , _A : Tuple=True , _A : Any=[0.5, 0.5, 0.5] , _A : str=[0.5, 0.5, 0.5] , _A : Any=True , ) -> str: """simple docstring""" snake_case_ : List[str] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} snake_case_ : str = parent snake_case_ : int = batch_size snake_case_ : Dict = num_channels snake_case_ : List[Any] = min_resolution snake_case_ : Optional[Any] = max_resolution snake_case_ : Optional[Any] = do_resize snake_case_ : Optional[int] = size snake_case_ : Union[str, Any] = do_rescale snake_case_ : List[Any] = rescale_factor snake_case_ : Optional[Any] = do_normalize snake_case_ : List[str] = image_mean snake_case_ : Dict = image_std snake_case_ : Optional[Any] = do_pad def UpperCAmelCase_ ( self : Dict ) -> 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 UpperCAmelCase_ ( self : int , _A : Dict , _A : int=False ) -> List[str]: """simple docstring""" if not batched: snake_case_ : List[str] = image_inputs[0] if isinstance(A__ , Image.Image ): snake_case_ ,snake_case_ : Tuple = image.size else: snake_case_ ,snake_case_ : str = image.shape[1], image.shape[2] if w < h: snake_case_ : int = int(self.size['shortest_edge'] * h / w ) snake_case_ : Optional[int] = self.size['shortest_edge'] elif w > h: snake_case_ : Optional[Any] = self.size['shortest_edge'] snake_case_ : Optional[int] = int(self.size['shortest_edge'] * w / h ) else: snake_case_ : Union[str, Any] = self.size['shortest_edge'] snake_case_ : Optional[int] = self.size['shortest_edge'] else: snake_case_ : Tuple = [] for image in image_inputs: snake_case_ ,snake_case_ : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) snake_case_ : Optional[Any] = max(A__ , key=lambda _A : item[0] )[0] snake_case_ : List[Any] = max(A__ , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): __magic_name__: Optional[int] = DetrImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" snake_case_ : str = DetrImageProcessingTester(self ) @property def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self : int ) -> str: """simple docstring""" snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , 'image_mean' ) ) self.assertTrue(hasattr(A__ , 'image_std' ) ) self.assertTrue(hasattr(A__ , 'do_normalize' ) ) self.assertTrue(hasattr(A__ , 'do_rescale' ) ) self.assertTrue(hasattr(A__ , 'rescale_factor' ) ) self.assertTrue(hasattr(A__ , 'do_resize' ) ) self.assertTrue(hasattr(A__ , 'size' ) ) self.assertTrue(hasattr(A__ , 'do_pad' ) ) def UpperCAmelCase_ ( self : Any ) -> int: """simple docstring""" snake_case_ : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , A__ ) snake_case_ : Any = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , A__ ) def UpperCAmelCase_ ( self : int ) -> List[str]: """simple docstring""" pass def UpperCAmelCase_ ( self : Optional[int] ) -> Any: """simple docstring""" snake_case_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values snake_case_ ,snake_case_ : Any = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ ,snake_case_ : Union[str, Any] = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) snake_case_ : List[Any] = image_processing(A__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self : Tuple ) -> int: """simple docstring""" snake_case_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , numpify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , np.ndarray ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values snake_case_ ,snake_case_ : Optional[Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Optional[Any] = image_processing(A__ , return_tensors='pt' ).pixel_values snake_case_ ,snake_case_ : Optional[Any] = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" snake_case_ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , torchify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , torch.Tensor ) # Test not batched input snake_case_ : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values snake_case_ ,snake_case_ : Union[str, Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Optional[int] = image_processing(A__ , return_tensors='pt' ).pixel_values snake_case_ ,snake_case_ : Dict = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" snake_case_ : Any = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: snake_case_ : List[str] = json.loads(f.read() ) snake_case_ : Any = {'image_id': 39769, 'annotations': target} # encode them snake_case_ : Dict = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) snake_case_ : Any = image_processing(images=A__ , annotations=A__ , return_tensors='pt' ) # verify pixel values snake_case_ : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , A__ ) snake_case_ : Tuple = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Tuple = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , A__ ) ) # verify boxes snake_case_ : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , A__ ) snake_case_ : str = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : str = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , A__ ) ) # verify is_crowd snake_case_ : Any = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , A__ ) ) # verify class_labels snake_case_ : Dict = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , A__ ) ) # verify orig_size snake_case_ : List[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , A__ ) ) # verify size snake_case_ : Tuple = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , A__ ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" snake_case_ : 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: snake_case_ : Any = json.loads(f.read() ) snake_case_ : List[Any] = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} snake_case_ : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them snake_case_ : Any = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) snake_case_ : int = image_processing(images=A__ , annotations=A__ , masks_path=A__ , return_tensors='pt' ) # verify pixel values snake_case_ : Optional[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , A__ ) snake_case_ : int = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Optional[int] = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , A__ ) ) # verify boxes snake_case_ : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , A__ ) snake_case_ : Dict = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , A__ ) ) # verify is_crowd snake_case_ : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , A__ ) ) # verify class_labels snake_case_ : List[Any] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , A__ ) ) # verify masks snake_case_ : Dict = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , A__ ) # verify orig_size snake_case_ : Union[str, Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , A__ ) ) # verify size snake_case_ : List[Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , A__ ) )
358
def SCREAMING_SNAKE_CASE__ ( __a , __a ): snake_case_ : Optional[int] = int(__a ) # Initialize Result snake_case_ : Tuple = [] # Traverse through all denomination for denomination in reversed(__a ): # Find denominations while int(__a ) >= int(__a ): total_value -= int(__a ) answer.append(__a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = """0""" if ( input("""Do you want to enter your denominations ? (yY/n): """).strip().lower() == "y" ): _SCREAMING_SNAKE_CASE = int(input("""Enter the number of denominations you want to add: """).strip()) for i in range(0, n): denominations.append(int(input(F'''Denomination {i}: ''').strip())) _SCREAMING_SNAKE_CASE = input("""Enter the change you want to make in Indian Currency: """).strip() else: # All denominations of Indian Currency if user does not enter _SCREAMING_SNAKE_CASE = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] _SCREAMING_SNAKE_CASE = input("""Enter the change you want to make: """).strip() if int(value) == 0 or int(value) < 0: print("""The total value cannot be zero or negative.""") else: print(F'''Following is minimal change for {value}: ''') _SCREAMING_SNAKE_CASE = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=""" """)
88
0
from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> str: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> str: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) def lowerCamelCase__ ( *__lowerCAmelCase : Union[str, Any] , **__lowerCAmelCase : Dict ): """simple docstring""" requires_backends(__lowerCAmelCase , ["torch"] ) def lowerCamelCase__ ( *__lowerCAmelCase : Optional[int] , **__lowerCAmelCase : int ): """simple docstring""" requires_backends(__lowerCAmelCase , ["torch"] ) def lowerCamelCase__ ( *__lowerCAmelCase : List[str] , **__lowerCAmelCase : int ): """simple docstring""" requires_backends(__lowerCAmelCase , ["torch"] ) def lowerCamelCase__ ( *__lowerCAmelCase : Union[str, Any] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" requires_backends(__lowerCAmelCase , ["torch"] ) def lowerCamelCase__ ( *__lowerCAmelCase : Dict , **__lowerCAmelCase : Any ): """simple docstring""" requires_backends(__lowerCAmelCase , ["torch"] ) def lowerCamelCase__ ( *__lowerCAmelCase : Optional[int] , **__lowerCAmelCase : Dict ): """simple docstring""" requires_backends(__lowerCAmelCase , ["torch"] ) def lowerCamelCase__ ( *__lowerCAmelCase : int , **__lowerCAmelCase : Any ): """simple docstring""" requires_backends(__lowerCAmelCase , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> str: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Union[str, Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Union[str, Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> str: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> str: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> int: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Any: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Tuple: requires_backends(cls , ["torch"] ) class _lowerCAmelCase ( metaclass=__a ): _lowercase =['''torch'''] def __init__( self , *_UpperCamelCase , **_UpperCamelCase ) -> str: requires_backends(self , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> Dict: requires_backends(cls , ["torch"] ) @classmethod def __a ( cls , *_UpperCamelCase , **_UpperCamelCase ) -> List[str]: requires_backends(cls , ["torch"] )
231
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() _A = logging.get_logger(__name__) def lowerCamelCase__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str=False ): """simple docstring""" lowerCAmelCase_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""deit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""deit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""deit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""deit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""deit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""deit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""deit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""deit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""deit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""deit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "deit.embeddings.cls_token"), ("dist_token", "deit.embeddings.distillation_token"), ("patch_embed.proj.weight", "deit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "deit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "deit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" lowerCAmelCase_ = [(pair[0], pair[1][4:]) if pair[1].startswith("deit" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("norm.weight", "deit.layernorm.weight"), ("norm.bias", "deit.layernorm.bias"), ("head.weight", "cls_classifier.weight"), ("head.bias", "cls_classifier.bias"), ("head_dist.weight", "distillation_classifier.weight"), ("head_dist.bias", "distillation_classifier.bias"), ] ) return rename_keys def lowerCamelCase__ ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: lowerCAmelCase_ = "" else: lowerCAmelCase_ = "deit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCAmelCase_ = state_dict.pop(F"""blocks.{i}.attn.qkv.weight""" ) lowerCAmelCase_ = state_dict.pop(F"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase_ = in_proj_weight[ : config.hidden_size, : ] lowerCAmelCase_ = in_proj_bias[: config.hidden_size] lowerCAmelCase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCAmelCase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCAmelCase_ = in_proj_weight[ -config.hidden_size :, : ] lowerCAmelCase_ = in_proj_bias[-config.hidden_size :] def lowerCamelCase__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Dict ): """simple docstring""" lowerCAmelCase_ = dct.pop(__lowerCAmelCase ) lowerCAmelCase_ = val def lowerCamelCase__ ( ): """simple docstring""" lowerCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase_ = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ) return im @torch.no_grad() def lowerCamelCase__ ( __lowerCAmelCase : List[str] , __lowerCAmelCase : str ): """simple docstring""" lowerCAmelCase_ = DeiTConfig() # all deit models have fine-tuned heads lowerCAmelCase_ = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size lowerCAmelCase_ = 1000 lowerCAmelCase_ = "huggingface/label-files" lowerCAmelCase_ = "imagenet-1k-id2label.json" lowerCAmelCase_ = json.load(open(hf_hub_download(__lowerCAmelCase , __lowerCAmelCase , repo_type="dataset" ) , "r" ) ) lowerCAmelCase_ = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} lowerCAmelCase_ = idalabel lowerCAmelCase_ = {v: k for k, v in idalabel.items()} lowerCAmelCase_ = int(deit_name[-6:-4] ) lowerCAmelCase_ = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("tiny" ): lowerCAmelCase_ = 192 lowerCAmelCase_ = 768 lowerCAmelCase_ = 12 lowerCAmelCase_ = 3 elif deit_name[9:].startswith("small" ): lowerCAmelCase_ = 384 lowerCAmelCase_ = 1536 lowerCAmelCase_ = 12 lowerCAmelCase_ = 6 if deit_name[9:].startswith("base" ): pass elif deit_name[4:].startswith("large" ): lowerCAmelCase_ = 1024 lowerCAmelCase_ = 4096 lowerCAmelCase_ = 24 lowerCAmelCase_ = 16 # load original model from timm lowerCAmelCase_ = timm.create_model(__lowerCAmelCase , pretrained=__lowerCAmelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowerCAmelCase_ = timm_model.state_dict() lowerCAmelCase_ = create_rename_keys(__lowerCAmelCase , __lowerCAmelCase ) for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) read_in_q_k_v(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # load HuggingFace model lowerCAmelCase_ = DeiTForImageClassificationWithTeacher(__lowerCAmelCase ).eval() model.load_state_dict(__lowerCAmelCase ) # Check outputs on an image, prepared by DeiTImageProcessor lowerCAmelCase_ = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 lowerCAmelCase_ = DeiTImageProcessor(size=__lowerCAmelCase , crop_size=config.image_size ) lowerCAmelCase_ = image_processor(images=prepare_img() , return_tensors="pt" ) lowerCAmelCase_ = encoding["pixel_values"] lowerCAmelCase_ = model(__lowerCAmelCase ) lowerCAmelCase_ = timm_model(__lowerCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__lowerCAmelCase , outputs.logits , atol=1e-3 ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) print(F"""Saving model {deit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__lowerCAmelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( "--deit_name", default="vit_deit_base_distilled_patch16_224", type=str, help="Name of the DeiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) _A = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
231
1
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def UpperCAmelCase_ ( __UpperCAmelCase : str , __UpperCAmelCase : str , **__UpperCAmelCase : List[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = AutoModelForSeqaSeqLM.from_config(__UpperCAmelCase ) model.save_pretrained(__UpperCAmelCase ) AutoTokenizer.from_pretrained(__UpperCAmelCase ).save_pretrained(__UpperCAmelCase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
210
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "" lowercase_ = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self : Optional[int] , _lowerCAmelCase : Optional[DatasetInfo] = None , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : int , ): super().__init__(self , **_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = repo_info SCREAMING_SNAKE_CASE_ = token SCREAMING_SNAKE_CASE_ = None def lowerCAmelCase_ ( self : Tuple ): if self.dir_cache is None: SCREAMING_SNAKE_CASE_ = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE_ = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(_lowerCAmelCase ): {'name': str(_lowerCAmelCase ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowerCAmelCase_ ( self : Optional[int] , _lowerCAmelCase : str , _lowerCAmelCase : str = "rb" , **_lowerCAmelCase : Optional[Any] , ): if not isinstance(self.repo_info , _lowerCAmelCase ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) SCREAMING_SNAKE_CASE_ = hf_hub_url(self.repo_info.id , _lowerCAmelCase , revision=self.repo_info.sha ) return fsspec.open( _lowerCAmelCase , mode=_lowerCAmelCase , headers=get_authentication_headers_for_url(_lowerCAmelCase , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def lowerCAmelCase_ ( self : List[Any] , _lowerCAmelCase : Any , **_lowerCAmelCase : Dict ): self._get_dirs() SCREAMING_SNAKE_CASE_ = self._strip_protocol(_lowerCAmelCase ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(_lowerCAmelCase ) def lowerCAmelCase_ ( self : Optional[Any] , _lowerCAmelCase : Any , _lowerCAmelCase : Any=False , **_lowerCAmelCase : str ): self._get_dirs() SCREAMING_SNAKE_CASE_ = PurePosixPath(path.strip('/' ) ) SCREAMING_SNAKE_CASE_ = {} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE_ = PurePosixPath(p.strip('/' ) ) SCREAMING_SNAKE_CASE_ = p.parent if root == path: SCREAMING_SNAKE_CASE_ = f SCREAMING_SNAKE_CASE_ = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
210
1
"""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 lowerCAmelCase__ = logging.getLogger(__name__) lowerCAmelCase__ = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) lowerCAmelCase__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class SCREAMING_SNAKE_CASE__ : """simple docstring""" a : Optional[str] =field( default=lowercase , metadata={ "help": ( "The model checkpoint for weights initialization. Leave None if you want to train a model from" " scratch." ) } , ) a : Optional[str] =field( default=lowercase , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(lowercase )} , ) a : Optional[str] =field( default=lowercase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) a : Optional[str] =field( default=lowercase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) a : Optional[str] =field( default=lowercase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class SCREAMING_SNAKE_CASE__ : """simple docstring""" a : Optional[str] =field( default=lowercase , metadata={"help": "The input training data file (a text file)."} ) a : 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" ) } , ) a : Optional[str] =field( default=lowercase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) a : Optional[str] =field( default=lowercase , metadata={"help": "An optional input train ref data file for whole word mask in Chinese."} , ) a : Optional[str] =field( default=lowercase , metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."} , ) a : bool =field( default=lowercase , metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."} , ) a : bool =field( default=lowercase , metadata={"help": "Train with masked-language modeling loss instead of language modeling."} ) a : bool =field(default=lowercase , metadata={"help": "Whether ot not to use whole word mask."} ) a : float =field( default=0.15 , metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} ) a : float =field( default=1 / 6 , metadata={ "help": ( "Ratio of length of a span of masked tokens to surrounding context length for permutation language" " modeling." ) } , ) a : int =field( default=5 , metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."} ) a : 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)." ) } , ) a : bool =field( default=lowercase , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def a__ ( SCREAMING_SNAKE_CASE : DataTrainingArguments , SCREAMING_SNAKE_CASE : PreTrainedTokenizer , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : Optional[str] = None , ): '''simple docstring''' def _dataset(SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[str]=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=SCREAMING_SNAKE_CASE , file_path=SCREAMING_SNAKE_CASE , block_size=args.block_size , ref_path=SCREAMING_SNAKE_CASE , ) return LineByLineTextDataset(tokenizer=SCREAMING_SNAKE_CASE , file_path=SCREAMING_SNAKE_CASE , block_size=args.block_size ) else: return TextDataset( tokenizer=SCREAMING_SNAKE_CASE , file_path=SCREAMING_SNAKE_CASE , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=SCREAMING_SNAKE_CASE , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(SCREAMING_SNAKE_CASE ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def a__ ( ): '''simple docstring''' lowerCAmelCase : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Dict = 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" , SCREAMING_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: lowerCAmelCase : int = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: lowerCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: lowerCAmelCase : Optional[Any] = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.tokenizer_name: lowerCAmelCase : Any = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: lowerCAmelCase : Dict = 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: lowerCAmelCase : Dict = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) else: logger.info("Training new model from scratch" ) lowerCAmelCase : int = AutoModelWithLMHead.from_config(SCREAMING_SNAKE_CASE ) model.resize_token_embeddings(len(SCREAMING_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: lowerCAmelCase : Dict = tokenizer.max_len # Our input block size will be the max possible for the model else: lowerCAmelCase : Optional[int] = min(data_args.block_size , tokenizer.max_len ) # Get datasets lowerCAmelCase : List[Any] = ( get_dataset(SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) lowerCAmelCase : Union[str, Any] = ( get_dataset(SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , evaluate=SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": lowerCAmelCase : int = DataCollatorForPermutationLanguageModeling( tokenizer=SCREAMING_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: lowerCAmelCase : Any = DataCollatorForWholeWordMask( tokenizer=SCREAMING_SNAKE_CASE , mlm_probability=data_args.mlm_probability ) else: lowerCAmelCase : List[str] = DataCollatorForLanguageModeling( tokenizer=SCREAMING_SNAKE_CASE , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer lowerCAmelCase : Any = Trainer( model=SCREAMING_SNAKE_CASE , args=SCREAMING_SNAKE_CASE , data_collator=SCREAMING_SNAKE_CASE , train_dataset=SCREAMING_SNAKE_CASE , eval_dataset=SCREAMING_SNAKE_CASE , prediction_loss_only=SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: lowerCAmelCase : List[str] = ( 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=SCREAMING_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 lowerCAmelCase : str = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase : List[str] = trainer.evaluate() lowerCAmelCase : Union[str, Any] = math.exp(eval_output["eval_loss"] ) lowerCAmelCase : Tuple = {"perplexity": perplexity} lowerCAmelCase : int = os.path.join(training_args.output_dir , "eval_results_lm.txt" ) if trainer.is_world_master(): with open(SCREAMING_SNAKE_CASE , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , SCREAMING_SNAKE_CASE , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) results.update(SCREAMING_SNAKE_CASE ) return results def a__ ( SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
108
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CodeGenTokenizer lowercase__ = CodeGenTokenizerFast lowercase__ = True lowercase__ = {"add_prefix_space": True} lowercase__ = False def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _snake_case : Tuple = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] _snake_case : Tuple = dict(zip(a_, range(len(a_ ) ) ) ) _snake_case : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _snake_case : List[Any] = {"""unk_token""": """<unk>"""} _snake_case : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) _snake_case : Optional[Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file, """w""", encoding="""utf-8""" ) as fp: fp.write(json.dumps(a_ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(a_ ) ) def UpperCamelCase_ ( self: Any, **a_: int ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Any, **a_: str ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **a_ ) def UpperCamelCase_ ( self: Union[str, Any], a_: Dict ): '''simple docstring''' _snake_case : Union[str, Any] = """lower newer""" _snake_case : Tuple = """lower newer""" return input_text, output_text def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : Union[str, Any] = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) _snake_case : Optional[Any] = """lower newer""" _snake_case : Optional[int] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] _snake_case : int = tokenizer.tokenize(a_, add_prefix_space=a_ ) self.assertListEqual(a_, a_ ) _snake_case : str = tokens + [tokenizer.unk_token] _snake_case : Optional[int] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : int = self.get_tokenizer() _snake_case : int = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : Dict = """lower newer""" # Testing tokenization _snake_case : Dict = tokenizer.tokenize(a_, add_prefix_space=a_ ) _snake_case : List[str] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids without special tokens _snake_case : Optional[Any] = tokenizer.encode(a_, add_special_tokens=a_, add_prefix_space=a_ ) _snake_case : Tuple = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # Testing conversion to ids with special tokens _snake_case : Tuple = self.get_rust_tokenizer(add_prefix_space=a_ ) _snake_case : int = tokenizer.encode(a_, add_prefix_space=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) # Testing the unknown token _snake_case : Tuple = tokens + [rust_tokenizer.unk_token] _snake_case : List[Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_ ), a_ ) def UpperCamelCase_ ( self: Dict, *a_: Dict, **a_: int ): '''simple docstring''' pass def UpperCamelCase_ ( self: int, a_: List[Any]=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _snake_case : List[Any] = self.rust_tokenizer_class.from_pretrained(a_, **a_ ) # Simple input _snake_case : Any = """This is a simple input""" _snake_case : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Optional[int] = ("""This is a simple input""", """This is a pair""") _snake_case : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Simple input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) # Pair input self.assertRaises(a_, tokenizer_r.encode, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises(a_, tokenizer_r.encode_plus, a_, max_length=a_, padding="""max_length""" ) # Pair input self.assertRaises( a_, tokenizer_r.batch_encode_plus, a_, max_length=a_, padding="""max_length""", ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token="""<pad>""" ) # Simple input _snake_case : List[Any] = """This is a simple input""" _snake_case : int = ["""This is a simple input looooooooong""", """This is a simple input"""] _snake_case : Any = ("""This is a simple input""", """This is a pair""") _snake_case : str = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] _snake_case : str = tokenizer.pad_token_id _snake_case : Optional[int] = tokenizer(a_, padding="""max_length""", max_length=30, return_tensors="""np""" ) _snake_case : Dict = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) _snake_case : Tuple = tokenizer(*a_, padding="""max_length""", max_length=60, return_tensors="""np""" ) _snake_case : Optional[Any] = tokenizer(a_, padding=a_, truncate=a_, return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Tuple = """$$$""" _snake_case : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=a_, add_bos_token=a_ ) _snake_case : str = """This is a simple input""" _snake_case : int = ["""This is a simple input 1""", """This is a simple input 2"""] _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Tuple = tokenizer(a_ ) _snake_case : Optional[Any] = tokenizer(a_ ) self.assertEqual(out_s.input_ids[0], a_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) _snake_case : Optional[int] = tokenizer.decode(out_s.input_ids ) _snake_case : int = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], a_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) _snake_case : Dict = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" _snake_case : Union[str, Any] = """\nif len_a > len_b: result = a\nelse: result = b""" _snake_case : Optional[Any] = tokenizer.encode(a_ ) _snake_case : Dict = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] _snake_case : Optional[Any] = tokenizer.decode(a_, truncate_before_pattern=a_ ) self.assertEqual(a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' pass
64
0
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __UpperCAmelCase (unittest.TestCase ,_UpperCAmelCase ): def UpperCamelCase ( self: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = load_tool("""text-to-speech""" ) self.tool.setup() def UpperCamelCase ( self: Any ): '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = self.tool("""hey""" ) _SCREAMING_SNAKE_CASE = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) , ) ) def UpperCamelCase ( self: List[Any] ): '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = self.tool("""hey""" ) _SCREAMING_SNAKE_CASE = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) , ) )
125
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCamelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ = 1_60_00 ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE = int(round(sample_rate * max_length ) ) if len(snake_case__ ) <= sample_length: return wav _SCREAMING_SNAKE_CASE = randint(0 ,len(snake_case__ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class __UpperCAmelCase : __snake_case : Optional[str] = field(default=_UpperCAmelCase ,metadata={"help": "Name of a dataset from the datasets package"} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "A file containing the training audio paths and labels."} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "A file containing the validation audio paths and labels."} ) __snake_case : str = field( default="train" ,metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } ,) __snake_case : str = field( default="validation" ,metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } ,) __snake_case : str = field( default="audio" ,metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} ,) __snake_case : str = field( default="label" ,metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) __snake_case : Optional[int] = field( default=_UpperCAmelCase ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } ,) __snake_case : Optional[int] = field( default=_UpperCAmelCase ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } ,) __snake_case : float = field( default=20 ,metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} ,) @dataclass class __UpperCAmelCase : __snake_case : str = field( default="facebook/wav2vec2-base" ,metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ,) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) __snake_case : str = field( default="main" ,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} ,) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Name or path of preprocessor config."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } ,) __snake_case : Optional[bool] = field( default=_UpperCAmelCase ,metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} ,) def UpperCamelCase ( self: List[str] ): '''simple docstring''' if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( """The argument `--freeze_feature_extractor` is deprecated and """ """will be removed in a future version. Use `--freeze_feature_encoder`""" """instead. Setting `freeze_feature_encoder==True`.""" , UpperCAmelCase_ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( """The argument `--freeze_feature_extractor` is deprecated and """ """should not be used in combination with `--freeze_feature_encoder`.""" """Only make use of `--freeze_feature_encoder`.""" ) def __lowerCamelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_audio_classification""" ,snake_case__ ,snake_case__ ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(snake_case__ ) transformers.utils.logging.set_verbosity(snake_case__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} ' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to train from scratch.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset and prepare it for the audio classification task. _SCREAMING_SNAKE_CASE = DatasetDict() _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.train_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.eval_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ' """Make sure to set `--audio_column_name` to the correct audio column - one of """ F'{", ".join(raw_datasets["train"].column_names )}.' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ' """Make sure to set `--label_column_name` to the correct text column - one of """ F'{", ".join(raw_datasets["train"].column_names )}.' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy _SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path ,return_attention_mask=model_args.attention_mask ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. _SCREAMING_SNAKE_CASE = raw_datasets.cast_column( data_args.audio_column_name ,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) _SCREAMING_SNAKE_CASE = feature_extractor.model_input_names[0] def train_transforms(snake_case__ ): _SCREAMING_SNAKE_CASE = [] for audio in batch[data_args.audio_column_name]: _SCREAMING_SNAKE_CASE = random_subsample( audio["""array"""] ,max_length=data_args.max_length_seconds ,sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(snake_case__ ) _SCREAMING_SNAKE_CASE = feature_extractor(snake_case__ ,sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(snake_case__ )} _SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(snake_case__ ): _SCREAMING_SNAKE_CASE = [audio["""array"""] for audio in batch[data_args.audio_column_name]] _SCREAMING_SNAKE_CASE = feature_extractor(snake_case__ ,sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(snake_case__ )} _SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _SCREAMING_SNAKE_CASE = raw_datasets["""train"""].features[data_args.label_column_name].names _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = {}, {} for i, label in enumerate(snake_case__ ): _SCREAMING_SNAKE_CASE = str(snake_case__ ) _SCREAMING_SNAKE_CASE = label # Load the accuracy metric from the datasets package _SCREAMING_SNAKE_CASE = evaluate.load("""accuracy""" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(snake_case__ ): _SCREAMING_SNAKE_CASE = np.argmax(eval_pred.predictions ,axis=1 ) return metric.compute(predictions=snake_case__ ,references=eval_pred.label_ids ) _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path ,num_labels=len(snake_case__ ) ,labelaid=snake_case__ ,idalabel=snake_case__ ,finetuning_task="""audio-classification""" ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) _SCREAMING_SNAKE_CASE = AutoModelForAudioClassification.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 ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE = ( raw_datasets["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(snake_case__ ,output_all_columns=snake_case__ ) if training_args.do_eval: if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE = ( raw_datasets["""eval"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(snake_case__ ,output_all_columns=snake_case__ ) # Initialize our trainer _SCREAMING_SNAKE_CASE = Trainer( model=snake_case__ ,args=snake_case__ ,train_dataset=raw_datasets["""train"""] if training_args.do_train else None ,eval_dataset=raw_datasets["""eval"""] if training_args.do_eval else None ,compute_metrics=snake_case__ ,tokenizer=snake_case__ ,) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE = last_checkpoint _SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=snake_case__ ) trainer.save_model() trainer.log_metrics("""train""" ,train_result.metrics ) trainer.save_metrics("""train""" ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE = trainer.evaluate() trainer.log_metrics("""eval""" ,snake_case__ ) trainer.save_metrics("""eval""" ,snake_case__ ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE = { """finetuned_from""": model_args.model_name_or_path, """tasks""": """audio-classification""", """dataset""": data_args.dataset_name, """tags""": ["""audio-classification"""], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case__ ) else: trainer.create_model_card(**snake_case__ ) if __name__ == "__main__": main()
125
1
from __future__ import annotations import math import random from typing import Any class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] ) ->None: lowerCamelCase__ : list[Any] = [] lowerCamelCase__ : int = 0 lowerCamelCase__ : int = 0 def __lowerCamelCase ( self : int ) ->bool: return self.head == self.tail def __lowerCamelCase ( self : Tuple , A : Any ) ->None: self.data.append(A ) lowerCamelCase__ : Any = self.tail + 1 def __lowerCamelCase ( self : int ) ->Any: lowerCamelCase__ : Optional[int] = self.data[self.head] lowerCamelCase__ : Optional[Any] = self.head + 1 return ret def __lowerCamelCase ( self : Optional[Any] ) ->int: return self.tail - self.head def __lowerCamelCase ( self : List[Any] ) ->None: print(self.data ) print('''**************''' ) print(self.data[self.head : self.tail] ) class __SCREAMING_SNAKE_CASE : def __init__( self : str , A : Any ) ->None: lowerCamelCase__ : int = data lowerCamelCase__ : MyNode | None = None lowerCamelCase__ : MyNode | None = None lowerCamelCase__ : int = 1 def __lowerCamelCase ( self : Optional[int] ) ->Any: return self.data def __lowerCamelCase ( self : Tuple ) ->MyNode | None: return self.left def __lowerCamelCase ( self : Optional[int] ) ->MyNode | None: return self.right def __lowerCamelCase ( self : Union[str, Any] ) ->int: return self.height def __lowerCamelCase ( self : Tuple , A : Any ) ->None: lowerCamelCase__ : Any = data def __lowerCamelCase ( self : Union[str, Any] , A : MyNode | None ) ->None: lowerCamelCase__ : str = node def __lowerCamelCase ( self : Dict , A : MyNode | None ) ->None: lowerCamelCase__ : List[Any] = node def __lowerCamelCase ( self : Dict , A : int ) ->None: lowerCamelCase__ : Any = height def _a ( UpperCAmelCase ) -> int: """simple docstring""" if node is None: return 0 return node.get_height() def _a ( UpperCAmelCase , UpperCAmelCase ) -> int: """simple docstring""" if a > b: return a return b def _a ( UpperCAmelCase ) -> MyNode: """simple docstring""" print('''left rotation node:''' , node.get_data() ) lowerCamelCase__ : str = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(UpperCAmelCase ) lowerCamelCase__ : List[str] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(UpperCAmelCase ) return ret def _a ( UpperCAmelCase ) -> MyNode: """simple docstring""" print('''right rotation node:''' , node.get_data() ) lowerCamelCase__ : int = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(UpperCAmelCase ) lowerCamelCase__ : Tuple = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(UpperCAmelCase ) lowerCamelCase__ : List[Any] = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(UpperCAmelCase ) return ret def _a ( UpperCAmelCase ) -> MyNode: """simple docstring""" lowerCamelCase__ : Tuple = node.get_left() assert left_child is not None node.set_left(left_rotation(UpperCAmelCase ) ) return right_rotation(UpperCAmelCase ) def _a ( UpperCAmelCase ) -> MyNode: """simple docstring""" lowerCamelCase__ : Dict = node.get_right() assert right_child is not None node.set_right(right_rotation(UpperCAmelCase ) ) return left_rotation(UpperCAmelCase ) def _a ( UpperCAmelCase , UpperCAmelCase ) -> MyNode | None: """simple docstring""" if node is None: return MyNode(UpperCAmelCase ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , UpperCAmelCase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected lowerCamelCase__ : Tuple = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child lowerCamelCase__ : List[Any] = right_rotation(UpperCAmelCase ) else: lowerCamelCase__ : Union[str, Any] = lr_rotation(UpperCAmelCase ) else: node.set_right(insert_node(node.get_right() , UpperCAmelCase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: lowerCamelCase__ : Any = node.get_right() assert right_child is not None if data < right_child.get_data(): lowerCamelCase__ : Any = rl_rotation(UpperCAmelCase ) else: lowerCamelCase__ : Any = left_rotation(UpperCAmelCase ) lowerCamelCase__ : List[str] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(UpperCAmelCase ) return node def _a ( UpperCAmelCase ) -> Any: """simple docstring""" while True: lowerCamelCase__ : Optional[Any] = root.get_right() if right_child is None: break lowerCamelCase__ : Any = right_child return root.get_data() def _a ( UpperCAmelCase ) -> Any: """simple docstring""" while True: lowerCamelCase__ : str = root.get_left() if left_child is None: break lowerCamelCase__ : List[Any] = left_child return root.get_data() def _a ( UpperCAmelCase , UpperCAmelCase ) -> MyNode | None: """simple docstring""" lowerCamelCase__ : Tuple = root.get_left() lowerCamelCase__ : Tuple = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: lowerCamelCase__ : List[str] = get_left_most(UpperCAmelCase ) root.set_data(UpperCAmelCase ) root.set_right(del_node(UpperCAmelCase , UpperCAmelCase ) ) elif left_child is not None: lowerCamelCase__ : List[str] = left_child elif right_child is not None: lowerCamelCase__ : Tuple = right_child else: return None elif root.get_data() > data: if left_child is None: print('''No such data''' ) return root else: root.set_left(del_node(UpperCAmelCase , UpperCAmelCase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(UpperCAmelCase , UpperCAmelCase ) ) if get_height(UpperCAmelCase ) - get_height(UpperCAmelCase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): lowerCamelCase__ : Dict = left_rotation(UpperCAmelCase ) else: lowerCamelCase__ : List[Any] = rl_rotation(UpperCAmelCase ) elif get_height(UpperCAmelCase ) - get_height(UpperCAmelCase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): lowerCamelCase__ : int = right_rotation(UpperCAmelCase ) else: lowerCamelCase__ : int = lr_rotation(UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(UpperCAmelCase ) return root class __SCREAMING_SNAKE_CASE : def __init__( self : Dict ) ->None: lowerCamelCase__ : MyNode | None = None def __lowerCamelCase ( self : str ) ->int: return get_height(self.root ) def __lowerCamelCase ( self : Optional[Any] , A : Any ) ->None: print('''insert:''' + str(A ) ) lowerCamelCase__ : Tuple = insert_node(self.root , A ) def __lowerCamelCase ( self : Union[str, Any] , A : Any ) ->None: print('''delete:''' + str(A ) ) if self.root is None: print('''Tree is empty!''' ) return lowerCamelCase__ : int = del_node(self.root , A ) def __str__( self : Tuple , ) ->str: # a level traversale, gives a more intuitive look on the tree lowerCamelCase__ : Any = '''''' lowerCamelCase__ : str = MyQueue() q.push(self.root ) lowerCamelCase__ : Any = self.get_height() if layer == 0: return output lowerCamelCase__ : List[Any] = 0 while not q.is_empty(): lowerCamelCase__ : Dict = q.pop() lowerCamelCase__ : Optional[int] = ''' ''' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(A ) q.push(A ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space lowerCamelCase__ : List[Any] = cnt + 1 for i in range(1_0_0 ): if cnt == math.pow(2 , A ) - 1: lowerCamelCase__ : List[Any] = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _a ( ) -> None: """simple docstring""" import doctest doctest.testmod() if __name__ == "__main__": _test() _A : Union[str, Any] = AVLtree() _A : Dict = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
142
from collections import namedtuple import requests from lxml import html # type: ignore _A : Any = namedtuple('covid_data', 'cases deaths recovered') def _a ( UpperCAmelCase = "https://www.worldometers.info/coronavirus/" ) -> covid_data: """simple docstring""" lowerCamelCase__ : Optional[Any] = '''//div[@class = "maincounter-number"]/span/text()''' return covid_data(*html.fromstring(requests.get(UpperCAmelCase ).content ).xpath(UpperCAmelCase ) ) _A : Dict = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
142
1
def _lowerCAmelCase ( __lowerCAmelCase ) -> List[Any]: """simple docstring""" stooge(__lowerCAmelCase , 0 , len(__lowerCAmelCase ) - 1 ) return arr def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: snake_case__ , snake_case__ : Union[str, Any] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: snake_case__ : Union[str, Any] = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(__lowerCAmelCase , __lowerCAmelCase , (h - t) ) # Recursively sort last 2/3 elements stooge(__lowerCAmelCase , i + t , (__lowerCAmelCase) ) # Recursively sort first 2/3 elements stooge(__lowerCAmelCase , __lowerCAmelCase , (h - t) ) if __name__ == "__main__": A__ = input('''Enter numbers separated by a comma:\n''').strip() A__ = [int(item) for item in user_input.split(''',''')] print(stooge_sort(unsorted))
44
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: """simple docstring""" snake_case__ : Optional[int] = len(__lowerCAmelCase ) + 1 snake_case__ : Tuple = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. snake_case__ : str = [[0 for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] # since string of zero length match pattern of zero length snake_case__ : int = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowerCAmelCase ): snake_case__ : Dict = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowerCAmelCase ): snake_case__ : str = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowerCAmelCase ): for j in range(1 , __lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": snake_case__ : Dict = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: snake_case__ : Union[str, Any] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): snake_case__ : List[str] = dp[i - 1][j] else: snake_case__ : Union[str, Any] = 0 else: snake_case__ : Tuple = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") A__ = '''aab''' A__ = '''c*a*b''' # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f"""{input_string} matches the given pattern {pattern}""") else: print(f"""{input_string} does not match with the given pattern {pattern}""")
44
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Dict = logging.get_logger(__name__) _A : Union[str, Any] = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): _UpperCAmelCase : Any = "vit_msn" def __init__( self : Optional[Any] , A : Dict=7_6_8 , A : Union[str, Any]=1_2 , A : Optional[Any]=1_2 , A : List[Any]=3_0_7_2 , A : List[str]="gelu" , A : Optional[int]=0.0 , A : int=0.0 , A : int=0.02 , A : Tuple=1e-06 , A : int=2_2_4 , A : Union[str, Any]=1_6 , A : Dict=3 , A : Optional[Any]=True , **A : Optional[Any] , ) ->Dict: super().__init__(**A ) lowerCamelCase__ : int = hidden_size lowerCamelCase__ : Dict = num_hidden_layers lowerCamelCase__ : str = num_attention_heads lowerCamelCase__ : Tuple = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : Optional[int] = hidden_dropout_prob lowerCamelCase__ : Any = attention_probs_dropout_prob lowerCamelCase__ : List[str] = initializer_range lowerCamelCase__ : Optional[int] = layer_norm_eps lowerCamelCase__ : Any = image_size lowerCamelCase__ : Any = patch_size lowerCamelCase__ : Union[str, Any] = num_channels lowerCamelCase__ : Tuple = qkv_bias
142
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Tuple , A : str , A : List[str]=1_0_0 , A : List[str]=1_3 , A : Union[str, Any]=3_0 , A : Union[str, Any]=2 , A : List[Any]=3 , A : Any=True , A : Tuple=True , A : Tuple=3_2 , A : str=5 , A : Any=4 , A : List[str]=3_7 , A : Tuple="gelu" , A : Union[str, Any]=0.1 , A : Tuple=0.1 , A : Union[str, Any]=1_0 , A : List[str]=0.02 , A : Dict=3 , ) ->int: lowerCamelCase__ : int = parent lowerCamelCase__ : Tuple = vocab_size lowerCamelCase__ : Dict = batch_size lowerCamelCase__ : str = image_size lowerCamelCase__ : Any = patch_size lowerCamelCase__ : str = num_channels lowerCamelCase__ : List[Any] = is_training lowerCamelCase__ : Tuple = use_labels lowerCamelCase__ : Dict = hidden_size lowerCamelCase__ : Optional[int] = num_hidden_layers lowerCamelCase__ : str = num_attention_heads lowerCamelCase__ : Tuple = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Any = attention_probs_dropout_prob lowerCamelCase__ : Tuple = type_sequence_label_size lowerCamelCase__ : List[Any] = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCamelCase__ : List[Any] = (image_size // patch_size) ** 2 lowerCamelCase__ : Tuple = num_patches + 1 def __lowerCamelCase ( self : Optional[int] ) ->List[Any]: lowerCamelCase__ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : List[str] = None if self.use_labels: lowerCamelCase__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Any = BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=A , initializer_range=self.initializer_range , ) return config, pixel_values, labels def __lowerCamelCase ( self : List[Any] , A : str , A : List[Any] , A : Any ) ->Tuple: lowerCamelCase__ : Union[str, Any] = FlaxBeitModel(config=A ) lowerCamelCase__ : int = model(A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self : Union[str, Any] , A : List[str] , A : Optional[int] , A : Dict ) ->Optional[int]: lowerCamelCase__ : Dict = FlaxBeitForMaskedImageModeling(config=A ) lowerCamelCase__ : Optional[Any] = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def __lowerCamelCase ( self : Union[str, Any] , A : Optional[Any] , A : Optional[int] , A : List[Any] ) ->Any: lowerCamelCase__ : Tuple = self.type_sequence_label_size lowerCamelCase__ : Tuple = FlaxBeitForImageClassification(config=A ) lowerCamelCase__ : Any = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCamelCase__ : Union[str, Any] = 1 lowerCamelCase__ : Optional[int] = FlaxBeitForImageClassification(A ) lowerCamelCase__ : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : List[str] = model(A ) def __lowerCamelCase ( self : Optional[Any] ) ->List[str]: lowerCamelCase__ : List[Any] = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : str = config_and_inputs lowerCamelCase__ : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ): _UpperCAmelCase : int = ( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def __lowerCamelCase ( self : str ) ->None: lowerCamelCase__ : Dict = FlaxBeitModelTester(self ) lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=A , has_text_modality=A , hidden_size=3_7 ) def __lowerCamelCase ( self : List[str] ) ->Any: self.config_tester.run_common_tests() def __lowerCamelCase ( self : str ) ->List[Any]: lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : List[str] = model_class(A ) lowerCamelCase__ : int = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : str = [*signature.parameters.keys()] lowerCamelCase__ : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , A ) def __lowerCamelCase ( self : int ) ->List[Any]: lowerCamelCase__ , lowerCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCamelCase__ : Union[str, Any] = self._prepare_for_class(A , A ) lowerCamelCase__ : Optional[int] = model_class(A ) @jax.jit def model_jitted(A : str , **A : Optional[int] ): return model(pixel_values=A , **A ) with self.subTest('''JIT Enabled''' ): lowerCamelCase__ : str = model_jitted(**A ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowerCamelCase__ : Dict = model_jitted(**A ).to_tuple() self.assertEqual(len(A ) , len(A ) ) for jitted_output, output in zip(A , A ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCamelCase ( self : Tuple ) ->Tuple: lowerCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def __lowerCamelCase ( self : Dict ) ->Any: lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A ) def __lowerCamelCase ( self : Any ) ->str: lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def __lowerCamelCase ( self : Optional[int] ) ->Tuple: for model_class_name in self.all_model_classes: lowerCamelCase__ : List[str] = model_class_name.from_pretrained('''microsoft/beit-base-patch16-224''' ) lowerCamelCase__ : Union[str, Any] = model(np.ones((1, 3, 2_2_4, 2_2_4) ) ) self.assertIsNotNone(A ) def _a ( ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__ : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @require_flax class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self : List[Any] ) ->Dict: return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224''' ) if is_vision_available() else None @slow def __lowerCamelCase ( self : str ) ->str: lowerCamelCase__ : List[str] = FlaxBeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k''' ) lowerCamelCase__ : Optional[Any] = self.default_image_processor lowerCamelCase__ : str = prepare_img() lowerCamelCase__ : Optional[int] = image_processor(images=A , return_tensors='''np''' ).pixel_values # prepare bool_masked_pos lowerCamelCase__ : List[str] = np.ones((1, 1_9_6) , dtype=A ) # forward pass lowerCamelCase__ : Optional[int] = model(pixel_values=A , bool_masked_pos=A ) lowerCamelCase__ : Optional[Any] = outputs.logits # verify the logits lowerCamelCase__ : str = (1, 1_9_6, 8_1_9_2) self.assertEqual(logits.shape , A ) lowerCamelCase__ : Any = np.array( [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , A , atol=1e-2 ) ) @slow def __lowerCamelCase ( self : Dict ) ->List[Any]: lowerCamelCase__ : Any = FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224''' ) lowerCamelCase__ : Dict = self.default_image_processor lowerCamelCase__ : List[str] = prepare_img() lowerCamelCase__ : int = image_processor(images=A , return_tensors='''np''' ) # forward pass lowerCamelCase__ : List[str] = model(**A ) lowerCamelCase__ : Optional[int] = outputs.logits # verify the logits lowerCamelCase__ : Union[str, Any] = (1, 1_0_0_0) self.assertEqual(logits.shape , A ) lowerCamelCase__ : Any = np.array([-1.23_85, -1.09_87, -1.01_08] ) self.assertTrue(np.allclose(logits[0, :3] , A , atol=1e-4 ) ) lowerCamelCase__ : Union[str, Any] = 2_8_1 self.assertEqual(logits.argmax(-1 ).item() , A ) @slow def __lowerCamelCase ( self : int ) ->Tuple: lowerCamelCase__ : List[Any] = FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k''' ) lowerCamelCase__ : Any = self.default_image_processor lowerCamelCase__ : Union[str, Any] = prepare_img() lowerCamelCase__ : Optional[Any] = image_processor(images=A , return_tensors='''np''' ) # forward pass lowerCamelCase__ : Union[str, Any] = model(**A ) lowerCamelCase__ : Any = outputs.logits # verify the logits lowerCamelCase__ : List[str] = (1, 2_1_8_4_1) self.assertEqual(logits.shape , A ) lowerCamelCase__ : str = np.array([1.68_81, -0.27_87, 0.59_01] ) self.assertTrue(np.allclose(logits[0, :3] , A , atol=1e-4 ) ) lowerCamelCase__ : List[Any] = 2_3_9_6 self.assertEqual(logits.argmax(-1 ).item() , A )
142
1
from collections.abc import Callable def _lowerCamelCase( lowercase__ , lowercase__ , lowercase__ ) -> float: '''simple docstring''' __lowercase= a __lowercase= b if function(lowercase__ ) == 0: # one of the a or b is a root for the function return a elif function(lowercase__ ) == 0: return b elif ( function(lowercase__ ) * function(lowercase__ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError('could not find root in given interval.' ) else: __lowercase= start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(lowercase__ ) == 0: return mid elif function(lowercase__ ) * function(lowercase__ ) < 0: __lowercase= mid else: __lowercase= mid __lowercase= start + (end - start) / 2.0 return mid def _lowerCamelCase( lowercase__ ) -> float: '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1_0_0_0)) import doctest doctest.testmod()
304
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging lowerCAmelCase = logging.get_logger(__name__) lowerCAmelCase = { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json''', # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class A ( A_ ): UpperCamelCase_ : Optional[int] ='''blenderbot-small''' UpperCamelCase_ : Optional[Any] =['''past_key_values'''] UpperCamelCase_ : Optional[int] ={'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__(self , lowerCAmelCase=5_0_2_6_5 , lowerCAmelCase=5_1_2 , lowerCAmelCase=8 , lowerCAmelCase=2_0_4_8 , lowerCAmelCase=1_6 , lowerCAmelCase=8 , lowerCAmelCase=2_0_4_8 , lowerCAmelCase=1_6 , lowerCAmelCase=0.0 , lowerCAmelCase=0.0 , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase="gelu" , lowerCAmelCase=5_1_2 , lowerCAmelCase=0.1 , lowerCAmelCase=0.0 , lowerCAmelCase=0.0 , lowerCAmelCase=0.02 , lowerCAmelCase=1 , lowerCAmelCase=False , lowerCAmelCase=0 , lowerCAmelCase=1 , lowerCAmelCase=2 , lowerCAmelCase=2 , **lowerCAmelCase , ): __lowercase= vocab_size __lowercase= max_position_embeddings __lowercase= d_model __lowercase= encoder_ffn_dim __lowercase= encoder_layers __lowercase= encoder_attention_heads __lowercase= decoder_ffn_dim __lowercase= decoder_layers __lowercase= decoder_attention_heads __lowercase= dropout __lowercase= attention_dropout __lowercase= activation_dropout __lowercase= activation_function __lowercase= init_std __lowercase= encoder_layerdrop __lowercase= decoder_layerdrop __lowercase= use_cache __lowercase= encoder_layers __lowercase= scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , is_encoder_decoder=lowerCAmelCase , decoder_start_token_id=lowerCAmelCase , forced_eos_token_id=lowerCAmelCase , **lowerCAmelCase , ) class A ( A_ ): @property def _A (self ): if self.task in ["default", "seq2seq-lm"]: __lowercase= OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: __lowercase= {0: 'batch'} __lowercase= {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __lowercase= {0: 'batch', 1: 'decoder_sequence'} __lowercase= {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase , direction='inputs' ) elif self.task == "causal-lm": # TODO: figure this case out. __lowercase= OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: __lowercase, __lowercase= self.num_layers for i in range(lowerCAmelCase ): __lowercase= {0: 'batch', 2: 'past_sequence + sequence'} __lowercase= {0: 'batch', 2: 'past_sequence + sequence'} else: __lowercase= OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}), ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}), ] ) return common_inputs @property def _A (self ): if self.task in ["default", "seq2seq-lm"]: __lowercase= super().outputs else: __lowercase= super(lowerCAmelCase , self ).outputs if self.use_past: __lowercase, __lowercase= self.num_layers for i in range(lowerCAmelCase ): __lowercase= {0: 'batch', 2: 'past_sequence + sequence'} __lowercase= {0: 'batch', 2: 'past_sequence + sequence'} return common_outputs def _A (self , lowerCAmelCase , lowerCAmelCase = -1 , lowerCAmelCase = -1 , lowerCAmelCase = False , lowerCAmelCase = None , ): __lowercase= self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # Generate decoder inputs __lowercase= seq_length if not self.use_past else 1 __lowercase= self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) __lowercase= {f'decoder_{name}': tensor for name, tensor in decoder_inputs.items()} __lowercase= dict(**lowerCAmelCase , **lowerCAmelCase ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __lowercase, __lowercase= common_inputs['input_ids'].shape __lowercase= common_inputs['decoder_input_ids'].shape[1] __lowercase, __lowercase= self.num_attention_heads __lowercase= ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __lowercase= decoder_seq_length + 3 __lowercase= ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __lowercase= torch.cat( [common_inputs['decoder_attention_mask'], torch.ones(lowerCAmelCase , lowerCAmelCase )] , dim=1 ) __lowercase= [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __lowercase, __lowercase= self.num_layers __lowercase= min(lowerCAmelCase , lowerCAmelCase ) __lowercase= max(lowerCAmelCase , lowerCAmelCase ) - min_num_layers __lowercase= 'encoder' if num_encoder_layers > num_decoder_layers else 'decoder' for _ in range(lowerCAmelCase ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase ), ) ) # TODO: test this. __lowercase= encoder_shape if remaining_side_name == 'encoder' else decoder_shape for _ in range(lowerCAmelCase , lowerCAmelCase ): common_inputs["past_key_values"].append((torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase )) ) return common_inputs def _A (self , lowerCAmelCase , lowerCAmelCase = -1 , lowerCAmelCase = -1 , lowerCAmelCase = False , lowerCAmelCase = None , ): __lowercase= self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __lowercase, __lowercase= common_inputs['input_ids'].shape # Not using the same length for past_key_values __lowercase= seqlen + 2 __lowercase, __lowercase= self.num_layers __lowercase, __lowercase= self.num_attention_heads __lowercase= ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __lowercase= common_inputs['attention_mask'].dtype __lowercase= torch.cat( [common_inputs['attention_mask'], torch.ones(lowerCAmelCase , lowerCAmelCase , dtype=lowerCAmelCase )] , dim=1 ) __lowercase= [ (torch.zeros(lowerCAmelCase ), torch.zeros(lowerCAmelCase )) for _ in range(lowerCAmelCase ) ] return common_inputs def _A (self , lowerCAmelCase , lowerCAmelCase = -1 , lowerCAmelCase = -1 , lowerCAmelCase = False , lowerCAmelCase = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __lowercase= compute_effective_axis_dimension( lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __lowercase= tokenizer.num_special_tokens_to_add(lowerCAmelCase ) __lowercase= compute_effective_axis_dimension( lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCAmelCase ) # Generate dummy inputs according to compute batch and sequence __lowercase= [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size __lowercase= dict(tokenizer(lowerCAmelCase , return_tensors=lowerCAmelCase ) ) return common_inputs def _A (self , lowerCAmelCase , lowerCAmelCase = -1 , lowerCAmelCase = -1 , lowerCAmelCase = False , lowerCAmelCase = None , ): if self.task in ["default", "seq2seq-lm"]: __lowercase= self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCAmelCase , batch_size=lowerCAmelCase , seq_length=lowerCAmelCase , is_pair=lowerCAmelCase , framework=lowerCAmelCase ) elif self.task == "causal-lm": __lowercase= self._generate_dummy_inputs_for_causal_lm( lowerCAmelCase , batch_size=lowerCAmelCase , seq_length=lowerCAmelCase , is_pair=lowerCAmelCase , framework=lowerCAmelCase ) else: __lowercase= self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCAmelCase , batch_size=lowerCAmelCase , seq_length=lowerCAmelCase , is_pair=lowerCAmelCase , framework=lowerCAmelCase ) return common_inputs def _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): if self.task in ["default", "seq2seq-lm"]: __lowercase= super()._flatten_past_key_values_(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) else: __lowercase= super(lowerCAmelCase , self )._flatten_past_key_values_( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
304
1
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def lowercase ( _snake_case : Dataset , _snake_case : Dict[str, str] ) ->List[str]: """simple docstring""" __snake_case : str = args.log_outputs __snake_case : Union[str, Any] = '''_'''.join(args.dataset.split('''/''' ) + [args.config, args.split] ) # load metric __snake_case : Dict = load_metric('''wer''' ) __snake_case : str = load_metric('''cer''' ) # compute metrics __snake_case : List[Any] = wer.compute(references=result['''target'''] , predictions=result['''prediction'''] ) __snake_case : Any = cer.compute(references=result['''target'''] , predictions=result['''prediction'''] ) # print & log results __snake_case : List[Any] = f"""WER: {wer_result}\nCER: {cer_result}""" print(_snake_case ) with open(f"""{dataset_id}_eval_results.txt""" , '''w''' ) as f: f.write(_snake_case ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: __snake_case : Optional[Any] = f"""log_{dataset_id}_predictions.txt""" __snake_case : Optional[int] = f"""log_{dataset_id}_targets.txt""" with open(_snake_case , '''w''' ) as p, open(_snake_case , '''w''' ) as t: # mapping function to write output def write_to_file(_snake_case : Dict , _snake_case : List[str] ): p.write(f"""{i}""" + '''\n''' ) p.write(batch['''prediction'''] + '''\n''' ) t.write(f"""{i}""" + '''\n''' ) t.write(batch['''target'''] + '''\n''' ) result.map(_snake_case , with_indices=_snake_case ) def lowercase ( _snake_case : str ) ->str: """simple docstring""" __snake_case : Any = '''[,?.!\-\;\:"“%‘”�—’…–]''' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training __snake_case : Dict = re.sub(_snake_case , '''''' , text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! __snake_case : Union[str, Any] = ['''\n\n''', '''\n''', ''' ''', ''' '''] for t in token_sequences_to_ignore: __snake_case : List[str] = ''' '''.join(text.split(_snake_case ) ) return text def lowercase ( _snake_case : Dict ) ->Any: """simple docstring""" __snake_case : Tuple = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=_snake_case ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor __snake_case : Dict = AutoFeatureExtractor.from_pretrained(args.model_id ) __snake_case : Union[str, Any] = feature_extractor.sampling_rate # resample audio __snake_case : Union[str, Any] = dataset.cast_column('''audio''' , Audio(sampling_rate=_snake_case ) ) # load eval pipeline if args.device is None: __snake_case : str = 0 if torch.cuda.is_available() else -1 __snake_case : Tuple = pipeline('''automatic-speech-recognition''' , model=args.model_id , device=args.device ) # map function to decode audio def map_to_pred(_snake_case : Union[str, Any] ): __snake_case : Any = asr( batch['''audio''']['''array'''] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s ) __snake_case : str = prediction['''text'''] __snake_case : Union[str, Any] = normalize_text(batch['''sentence'''] ) return batch # run inference on all examples __snake_case : Optional[Any] = dataset.map(_snake_case , remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(_snake_case , _snake_case ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument( """--model_id""", type=str, required=True, help="""Model identifier. Should be loadable with 🤗 Transformers""" ) parser.add_argument( """--dataset""", type=str, required=True, help="""Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets""", ) parser.add_argument( """--config""", type=str, required=True, help="""Config of the dataset. *E.g.* `'en'` for Common Voice""" ) parser.add_argument("""--split""", type=str, required=True, help="""Split of the dataset. *E.g.* `'test'`""") parser.add_argument( """--chunk_length_s""", type=float, default=None, help="""Chunk length in seconds. Defaults to 5 seconds.""" ) parser.add_argument( """--stride_length_s""", type=float, default=None, help="""Stride of the audio chunks. Defaults to 1 second.""" ) parser.add_argument( """--log_outputs""", action="""store_true""", help="""If defined, write outputs to log file for analysis.""" ) parser.add_argument( """--device""", type=int, default=None, help="""The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.""", ) SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() main(args)
102
"""simple docstring""" from sklearn.metrics import recall_score import datasets SCREAMING_SNAKE_CASE : Dict = """ Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is the false negatives. """ SCREAMING_SNAKE_CASE : Any = """ Args: - **predictions** (`list` of `int`): The predicted labels. - **references** (`list` of `int`): The ground truth labels. - **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. - **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`. - **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). - **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. - **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised. - `0`: If there is a zero division, the return value is `0`. - `1`: If there is a zero division, the return value is `1`. Returns: - **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. Examples: Example 1-A simple example with some errors >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) >>> print(results) {'recall': 0.6666666666666666} Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) >>> print(results) {'recall': 0.5} Example 3-The same example as Example 1, but with `sample_weight` included. >>> recall_metric = datasets.load_metric('recall') >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) >>> print(results) {'recall': 0.55} Example 4-A multiclass example, using different averages. >>> recall_metric = datasets.load_metric('recall') >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'recall': array([1., 0., 0.])} """ SCREAMING_SNAKE_CASE : Tuple = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html'''] , ) def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_=None , a_=1 , a_="binary" , a_=None , a_="warn" , ): '''simple docstring''' __snake_case : Any = recall_score( a_ , a_ , labels=a_ , pos_label=a_ , average=a_ , sample_weight=a_ , zero_division=a_ , ) return {"recall": float(a_ ) if score.size == 1 else score}
102
1
'''simple docstring''' 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 __a ( _UpperCamelCase: Optional[Any] ) -> Tuple: """simple docstring""" _snake_case = 384 if "tiny" in model_name: _snake_case = [3, 3, 9, 3] _snake_case = [96, 192, 384, 768] if "small" in model_name: _snake_case = [3, 3, 27, 3] _snake_case = [96, 192, 384, 768] if "base" in model_name: _snake_case = [3, 3, 27, 3] _snake_case = [128, 256, 512, 1_024] _snake_case = 512 if "large" in model_name: _snake_case = [3, 3, 27, 3] _snake_case = [192, 384, 768, 1_536] _snake_case = 768 if "xlarge" in model_name: _snake_case = [3, 3, 27, 3] _snake_case = [256, 512, 1_024, 2_048] _snake_case = 1_024 # set label information _snake_case = 150 _snake_case = "huggingface/label-files" _snake_case = "ade20k-id2label.json" _snake_case = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type="dataset" ) , "r" ) ) _snake_case = {int(_UpperCamelCase ): v for k, v in idalabel.items()} _snake_case = {v: k for k, v in idalabel.items()} _snake_case = ConvNextConfig( depths=_UpperCamelCase , hidden_sizes=_UpperCamelCase , out_features=["stage1", "stage2", "stage3", "stage4"] ) _snake_case = UperNetConfig( backbone_config=_UpperCamelCase , auxiliary_in_channels=_UpperCamelCase , num_labels=_UpperCamelCase , idalabel=_UpperCamelCase , labelaid=_UpperCamelCase , ) return config def __a ( _UpperCamelCase: Dict ) -> Optional[int]: """simple docstring""" _snake_case = [] # 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 __a ( _UpperCamelCase: Any , _UpperCamelCase: Union[str, Any] , _UpperCamelCase: Dict ) -> Union[str, Any]: """simple docstring""" _snake_case = dct.pop(_UpperCamelCase ) _snake_case = val def __a ( _UpperCamelCase: Optional[Any] , _UpperCamelCase: int , _UpperCamelCase: Dict ) -> Dict: """simple docstring""" _snake_case = { "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", } _snake_case = model_name_to_url[model_name] _snake_case = torch.hub.load_state_dict_from_url(_UpperCamelCase , map_location="cpu" )["state_dict"] _snake_case = get_upernet_config(_UpperCamelCase ) _snake_case = UperNetForSemanticSegmentation(_UpperCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): _snake_case = state_dict.pop(_UpperCamelCase ) if "bn" in key: _snake_case = key.replace("bn" , "batch_norm" ) _snake_case = val # rename keys _snake_case = create_rename_keys(_UpperCamelCase ) for src, dest in rename_keys: rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # verify on image _snake_case = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg" _snake_case = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert("RGB" ) _snake_case = SegformerImageProcessor() _snake_case = processor(_UpperCamelCase , return_tensors="pt" ).pixel_values with torch.no_grad(): _snake_case = model(_UpperCamelCase ) if model_name == "upernet-convnext-tiny": _snake_case = 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": _snake_case = 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": _snake_case = 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": _snake_case = 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": _snake_case = 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] , _UpperCamelCase , atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_UpperCamelCase ) print(F"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(_UpperCamelCase ) if push_to_hub: print(F"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(F"""openmmlab/{model_name}""" ) processor.push_to_hub(F"""openmmlab/{model_name}""" ) if __name__ == "__main__": UpperCamelCase_ : List[str] = 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.''' ) UpperCamelCase_ : Optional[Any] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
142
'''simple docstring''' from manim import * class _a ( __lowerCAmelCase ): def _lowercase ( self ) -> Optional[int]: _snake_case = Rectangle(height=0.5 ,width=0.5 ) _snake_case = Rectangle(height=0.4_6 ,width=0.4_6 ).set_stroke(width=0 ) _snake_case = [mem.copy() for i in range(6 )] _snake_case = [mem.copy() for i in range(6 )] _snake_case = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0 ) _snake_case = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0 ) _snake_case = VGroup(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0 ) _snake_case = Text("CPU" ,font_size=24 ) _snake_case = Group(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0.5 ,aligned_edge=_SCREAMING_SNAKE_CASE ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_SCREAMING_SNAKE_CASE ) _snake_case = [mem.copy() for i in range(4 )] _snake_case = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0 ) _snake_case = Text("GPU" ,font_size=24 ) _snake_case = Group(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0.5 ,aligned_edge=_SCREAMING_SNAKE_CASE ) gpu.move_to([-1, -1, 0] ) self.add(_SCREAMING_SNAKE_CASE ) _snake_case = [mem.copy() for i in range(6 )] _snake_case = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0 ) _snake_case = Text("Model" ,font_size=24 ) _snake_case = Group(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0.5 ,aligned_edge=_SCREAMING_SNAKE_CASE ) model.move_to([3, -1.0, 0] ) self.add(_SCREAMING_SNAKE_CASE ) _snake_case = [] for i, rect in enumerate(_SCREAMING_SNAKE_CASE ): rect.set_stroke(_SCREAMING_SNAKE_CASE ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) _snake_case = Rectangle(height=0.4_6 / 4 ,width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(_SCREAMING_SNAKE_CASE ,opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) ,buff=0.0_2 ,direction=_SCREAMING_SNAKE_CASE ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] ,direction=_SCREAMING_SNAKE_CASE ,buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] ,direction=_SCREAMING_SNAKE_CASE ,buff=0.0 ) self.add(_SCREAMING_SNAKE_CASE ) cpu_targs.append(_SCREAMING_SNAKE_CASE ) _snake_case = [mem.copy() for i in range(6 )] _snake_case = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,buff=0 ) _snake_case = Text("Loaded Checkpoint" ,font_size=24 ) _snake_case = Group(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE ,aligned_edge=_SCREAMING_SNAKE_CASE ,buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) _snake_case = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _snake_case = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" ,font_size=18 ,) key_text.move_to([-5, 2.4, 0] ) self.add(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) _snake_case = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" ,font_size=18 ,) blue_text.next_to(_SCREAMING_SNAKE_CASE ,DOWN * 2.4 ,aligned_edge=key_text.get_left() ) _snake_case = MarkupText( f"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>.""" ,font_size=24 ,) step_a.move_to([2, 2, 0] ) self.play(Write(_SCREAMING_SNAKE_CASE ) ,Write(_SCREAMING_SNAKE_CASE ) ) self.play(Write(_SCREAMING_SNAKE_CASE ,run_time=1 ) ,Create(_SCREAMING_SNAKE_CASE ,run_time=1 ) ) _snake_case = [] _snake_case = [] for i, rect in enumerate(_SCREAMING_SNAKE_CASE ): _snake_case = fill.copy().set_fill(_SCREAMING_SNAKE_CASE ,opacity=0.7 ) target.move_to(_SCREAMING_SNAKE_CASE ) first_animations.append(GrowFromCenter(_SCREAMING_SNAKE_CASE ,run_time=1 ) ) _snake_case = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(_SCREAMING_SNAKE_CASE ,run_time=1.5 ) ) self.play(*_SCREAMING_SNAKE_CASE ) self.play(*_SCREAMING_SNAKE_CASE ) self.wait()
142
1
from typing import TYPE_CHECKING from ...utils import _LazyModule a__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys a__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
317
import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import logging a__ = ["""bart.large""", """bart.large.mnli""", """bart.large.cnn""", """bart_xsum/model.pt"""] a__ = {"""bart.large""": BartModel, """bart.large.mnli""": BartForSequenceClassification} if version.parse(fairseq.__version__) < version.parse("""0.9.0"""): raise Exception("""requires fairseq >= 0.9.0""") logging.set_verbosity_info() a__ = logging.get_logger(__name__) a__ = """ Hello world! cécé herlolip""" a__ = [ ("""model.classification_heads.mnli.dense.weight""", """classification_head.dense.weight"""), ("""model.classification_heads.mnli.dense.bias""", """classification_head.dense.bias"""), ("""model.classification_heads.mnli.out_proj.weight""", """classification_head.out_proj.weight"""), ("""model.classification_heads.mnli.out_proj.bias""", """classification_head.out_proj.bias"""), ] def lowercase ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: _snake_case : Union[str, Any] = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """_float_tensor""", ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowercase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: _snake_case : Optional[int] = dct.pop(SCREAMING_SNAKE_CASE__ ) _snake_case : int = val def lowercase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: _snake_case : List[Any] = torch.load(SCREAMING_SNAKE_CASE__ , map_location="""cpu""" ) _snake_case : int = torch.hub.load("""pytorch/fairseq""" , """bart.large.cnn""" ).eval() hub_interface.model.load_state_dict(sd["""model"""] ) return hub_interface def lowercase ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: _snake_case , _snake_case : List[str] = emb.weight.shape _snake_case : Any = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = emb.weight.data return lin_layer @torch.no_grad() def lowercase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str=None ) -> List[str]: if not os.path.exists(SCREAMING_SNAKE_CASE__ ): _snake_case : List[str] = torch.hub.load("""pytorch/fairseq""" , SCREAMING_SNAKE_CASE__ ).eval() else: _snake_case : Union[str, Any] = load_xsum_checkpoint(SCREAMING_SNAKE_CASE__ ) bart.model.upgrade_state_dict(bart.model.state_dict() ) if hf_checkpoint_name is None: _snake_case : Optional[Any] = checkpoint_path.replace(""".""" , """-""" ) _snake_case : Optional[Any] = BartConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) _snake_case : List[Any] = bart.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) _snake_case : str = BartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ).encode(SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" ).unsqueeze(0 ) if not torch.eq(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).all(): raise ValueError( F'''converted tokenizer and pretrained tokenizer returned different output: {tokens} != {tokensa}''' ) if checkpoint_path == "bart.large.mnli": _snake_case : Dict = bart.state_dict() remove_ignore_keys_(SCREAMING_SNAKE_CASE__ ) _snake_case : str = state_dict["""model.decoder.embed_tokens.weight"""] for src, dest in mnli_rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = BartForSequenceClassification(SCREAMING_SNAKE_CASE__ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = bart.predict("""mnli""" , SCREAMING_SNAKE_CASE__ , return_logits=SCREAMING_SNAKE_CASE__ ) _snake_case : Optional[int] = model(SCREAMING_SNAKE_CASE__ )[0] # logits else: # no classification heads to worry about _snake_case : Dict = bart.model.state_dict() remove_ignore_keys_(SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = state_dict["""decoder.embed_tokens.weight"""] _snake_case : Optional[Any] = bart.extract_features(SCREAMING_SNAKE_CASE__ ) if hf_checkpoint_name == "facebook/bart-large": _snake_case : Optional[Any] = BartModel(SCREAMING_SNAKE_CASE__ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) _snake_case : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ).model[0] else: _snake_case : str = BartForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() # an existing summarization ckpt model.model.load_state_dict(SCREAMING_SNAKE_CASE__ ) if hasattr(SCREAMING_SNAKE_CASE__ , """lm_head""" ): _snake_case : Any = make_linear_from_emb(model.model.shared ) _snake_case : Optional[Any] = model.model(SCREAMING_SNAKE_CASE__ )[0] # Check results if fairseq_output.shape != new_model_outputs.shape: raise ValueError( F'''`fairseq_output` shape and `new_model_output` shape are different: {fairseq_output.shape=}, {new_model_outputs.shape}''' ) if (fairseq_output != new_model_outputs).any().item(): raise ValueError("""Some values in `fairseq_output` are different from `new_model_outputs`""" ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": a__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """fairseq_path""", type=str, help="""bart.large, bart.large.cnn or a path to a model.pt on local filesystem.""" ) parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--hf_config""", default=None, type=str, help="""Which huggingface architecture to use: bart-large-xsum""" ) a__ = parser.parse_args() convert_bart_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, hf_checkpoint_name=args.hf_config)
317
1
'''simple docstring''' from itertools import permutations def UpperCAmelCase_ ( __lowercase : tuple ) -> bool: '''simple docstring''' if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False _UpperCAmelCase = [7, 11, 13, 17] for i, test in enumerate(SCREAMING_SNAKE_CASE_ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def UpperCAmelCase_ ( __lowercase : int = 10 ) -> int: '''simple docstring''' return sum( int("".join(map(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) for num in permutations(range(SCREAMING_SNAKE_CASE_ ) ) if is_substring_divisible(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": print(F"{solution() = }")
366
'''simple docstring''' from sklearn.metrics import recall_score import datasets __SCREAMING_SNAKE_CASE :Any = ''' Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is the false negatives. ''' __SCREAMING_SNAKE_CASE :Tuple = ''' Args: - **predictions** (`list` of `int`): The predicted labels. - **references** (`list` of `int`): The ground truth labels. - **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. - **pos_label** (`int`): The class label to use as the \'positive class\' when calculating the recall. Defaults to `1`. - **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`. - `\'binary\'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - `\'micro\'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - `\'macro\'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - `\'weighted\'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - `\'samples\'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). - **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. - **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - `\'warn\'`: If there is a zero division, the return value is `0`, but warnings are also raised. - `0`: If there is a zero division, the return value is `0`. - `1`: If there is a zero division, the return value is `1`. Returns: - **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. Examples: Example 1-A simple example with some errors >>> recall_metric = datasets.load_metric(\'recall\') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) >>> print(results) {\'recall\': 0.6666666666666666} Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. >>> recall_metric = datasets.load_metric(\'recall\') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) >>> print(results) {\'recall\': 0.5} Example 3-The same example as Example 1, but with `sample_weight` included. >>> recall_metric = datasets.load_metric(\'recall\') >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) >>> print(results) {\'recall\': 0.55} Example 4-A multiclass example, using different averages. >>> recall_metric = datasets.load_metric(\'recall\') >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'macro\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'micro\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'weighted\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {\'recall\': array([1., 0., 0.])} ''' __SCREAMING_SNAKE_CASE :Optional[int] = ''' @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowercase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"] , ) def lowercase ( self : Tuple , snake_case_ : Optional[int] , snake_case_ : Optional[int] , snake_case_ : Optional[int]=None , snake_case_ : str=1 , snake_case_ : str="binary" , snake_case_ : int=None , snake_case_ : List[Any]="warn" , ): _UpperCAmelCase = recall_score( snake_case_ , snake_case_ , labels=snake_case_ , pos_label=snake_case_ , average=snake_case_ , sample_weight=snake_case_ , zero_division=snake_case_ , ) return {"recall": float(snake_case_ ) if score.size == 1 else score}
156
0
from __future__ import annotations def lowerCamelCase__ ( snake_case_ : list[int | str] ) -> None: create_state_space_tree(snake_case_ , [] , 0 , [0 for i in range(len(snake_case_ ) )] ) def lowerCamelCase__ ( snake_case_ : list[int | str] , snake_case_ : list[int | str] , snake_case_ : int , snake_case_ : list[int] , ) -> None: if index == len(snake_case_ ): print(snake_case_ ) return for i in range(len(snake_case_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) __snake_case = True create_state_space_tree(snake_case_ , snake_case_ , index + 1 , snake_case_ ) current_sequence.pop() __snake_case = False snake_case_ = [3, 1, 2, 4] generate_all_permutations(sequence) snake_case_ = ["A", "B", "C"] generate_all_permutations(sequence_a)
24
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( "stable diffusion controlnet", "0.22.0", "Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.", standard_warn=False, stacklevel=3, )
237
0
"""simple docstring""" import operator as op def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> int: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = lambda SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('Symbol'.center(8 ) , 'Action'.center(12 ) , 'Stack' , sep=' | ' ) print('-' * (30 + len(SCREAMING_SNAKE_CASE_ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(SCREAMING_SNAKE_CASE_ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('push(' + x + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) else: SCREAMING_SNAKE_CASE = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + b + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) SCREAMING_SNAKE_CASE = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + a + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) stack.append( str(opr[x](int(SCREAMING_SNAKE_CASE_ ) , int(SCREAMING_SNAKE_CASE_ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' , ) return int(stack[0] ) if __name__ == "__main__": __UpperCamelCase = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''') print('''\n\tResult = ''', solve(Postfix))
38
"""simple docstring""" import operator as op def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> int: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = lambda SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('Symbol'.center(8 ) , 'Action'.center(12 ) , 'Stack' , sep=' | ' ) print('-' * (30 + len(SCREAMING_SNAKE_CASE_ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(SCREAMING_SNAKE_CASE_ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('push(' + x + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) else: SCREAMING_SNAKE_CASE = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + b + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) SCREAMING_SNAKE_CASE = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + a + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) stack.append( str(opr[x](int(SCREAMING_SNAKE_CASE_ ) , int(SCREAMING_SNAKE_CASE_ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' , ) return int(stack[0] ) if __name__ == "__main__": __UpperCamelCase = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''') print('''\n\tResult = ''', solve(Postfix))
38
1
'''simple docstring''' import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib _A : str = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } _A : Optional[int] = logging.WARNING def UpperCamelCase_ ( ) -> List[Any]: '''simple docstring''' __lowerCAmelCase = os.getenv("""DATASETS_VERBOSITY""" , snake_case_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f"""Unknown option DATASETS_VERBOSITY={env_level_str}, """ f"""has to be one of: { ", ".join(log_levels.keys() ) }""" ) return _default_log_level def UpperCamelCase_ ( ) -> str: '''simple docstring''' return __name__.split(""".""" )[0] def UpperCamelCase_ ( ) -> logging.Logger: '''simple docstring''' return logging.getLogger(_get_library_name() ) def UpperCamelCase_ ( ) -> None: '''simple docstring''' __lowerCAmelCase = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def UpperCamelCase_ ( ) -> None: '''simple docstring''' __lowerCAmelCase = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def UpperCamelCase_ ( snake_case_ : Optional[str] = None ) -> logging.Logger: '''simple docstring''' if name is None: __lowerCAmelCase = _get_library_name() return logging.getLogger(snake_case_ ) def UpperCamelCase_ ( ) -> int: '''simple docstring''' return _get_library_root_logger().getEffectiveLevel() def UpperCamelCase_ ( snake_case_ : int ) -> None: '''simple docstring''' _get_library_root_logger().setLevel(snake_case_ ) def UpperCamelCase_ ( ) -> int: '''simple docstring''' return set_verbosity(snake_case_ ) def UpperCamelCase_ ( ) -> List[str]: '''simple docstring''' return set_verbosity(snake_case_ ) def UpperCamelCase_ ( ) -> List[str]: '''simple docstring''' return set_verbosity(snake_case_ ) def UpperCamelCase_ ( ) -> int: '''simple docstring''' return set_verbosity(snake_case_ ) def UpperCamelCase_ ( ) -> None: '''simple docstring''' __lowerCAmelCase = False def UpperCamelCase_ ( ) -> None: '''simple docstring''' __lowerCAmelCase = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class _lowercase : '''simple docstring''' def __init__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> int: # pylint: disable=unused-argument __lowerCAmelCase = args[0] if args else None def __iter__( self : Optional[int] ) -> Optional[Any]: return iter(self._iterator ) def __getattr__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> str: def empty_fn(*SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : List[Any] ) -> Tuple: return self def __exit__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: return _A : Any = True class _lowercase : '''simple docstring''' def __call__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: if _tqdm_active and not disable: return tqdm_lib.tqdm(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: return EmptyTqdm(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: __lowerCAmelCase = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Dict ) -> List[str]: if _tqdm_active: return tqdm_lib.tqdm.get_lock() _A : Optional[Any] = _tqdm_cls() def UpperCamelCase_ ( ) -> bool: '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def UpperCamelCase_ ( ) -> List[str]: '''simple docstring''' global _tqdm_active __lowerCAmelCase = True def UpperCamelCase_ ( ) -> int: '''simple docstring''' global _tqdm_active __lowerCAmelCase = False
229
'''simple docstring''' import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() _A : str = logging.get_logger(__name__) _A : str = [ ['''attention''', '''attn'''], ['''encoder_attention''', '''encoder_attn'''], ['''q_lin''', '''q_proj'''], ['''k_lin''', '''k_proj'''], ['''v_lin''', '''v_proj'''], ['''out_lin''', '''out_proj'''], ['''norm_embeddings''', '''layernorm_embedding'''], ['''position_embeddings''', '''embed_positions'''], ['''embeddings''', '''embed_tokens'''], ['''ffn.lin''', '''fc'''], ] def UpperCamelCase_ ( snake_case_ : Tuple ) -> Optional[int]: '''simple docstring''' if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __lowerCAmelCase = k.replace(snake_case_ , snake_case_ ) if k.startswith("""encoder""" ): __lowerCAmelCase = k.replace(""".attn""" , """.self_attn""" ) __lowerCAmelCase = k.replace("""norm1""" , """self_attn_layer_norm""" ) __lowerCAmelCase = k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): __lowerCAmelCase = k.replace("""norm1""" , """self_attn_layer_norm""" ) __lowerCAmelCase = k.replace("""norm2""" , """encoder_attn_layer_norm""" ) __lowerCAmelCase = k.replace("""norm3""" , """final_layer_norm""" ) return k def UpperCamelCase_ ( snake_case_ : List[str] ) -> Dict: '''simple docstring''' __lowerCAmelCase = [ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: __lowerCAmelCase = sd.pop(snake_case_ ) __lowerCAmelCase = k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd __lowerCAmelCase = v _A : int = ['''START'''] @torch.no_grad() def UpperCamelCase_ ( snake_case_ : List[Any] , snake_case_ : Any , snake_case_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' __lowerCAmelCase = torch.load(snake_case_ , map_location="""cpu""" ) __lowerCAmelCase = model["""model"""] __lowerCAmelCase = BlenderbotConfig.from_json_file(snake_case_ ) __lowerCAmelCase = BlenderbotForConditionalGeneration(snake_case_ ) __lowerCAmelCase = m.model.state_dict().keys() __lowerCAmelCase = [] __lowerCAmelCase = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue __lowerCAmelCase = rename_state_dict_key(snake_case_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __lowerCAmelCase = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(snake_case_ ) m.model.load_state_dict(snake_case_ , strict=snake_case_ ) m.half() m.save_pretrained(snake_case_ ) if __name__ == "__main__": _A : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('''--src_path''', type=str, help='''like blenderbot-model.bin''') parser.add_argument('''--save_dir''', default='''hf_blenderbot''', type=str, help='''Where to save converted model.''') parser.add_argument( '''--hf_config_json''', default='''blenderbot-3b-config.json''', type=str, help='''Path to config to use''' ) _A : Tuple = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
229
1
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def A ( _lowerCamelCase = 8 ): '''simple docstring''' _lowerCAmelCase : List[Any] = ascii_letters + digits + punctuation return "".join(secrets.choice(lowerCamelCase__ ) for _ in range(lowerCamelCase__ ) ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' i -= len(lowerCamelCase__ ) _lowerCAmelCase : Tuple = i // 3 _lowerCAmelCase : Tuple = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) _lowerCAmelCase : List[str] = ( chars_incl + random(lowerCamelCase__ , quotient + remainder ) + random(lowerCamelCase__ , lowerCamelCase__ ) + random(lowerCamelCase__ , lowerCamelCase__ ) ) _lowerCAmelCase : int = list(lowerCamelCase__ ) shuffle(lowerCamelCase__ ) return "".join(lowerCamelCase__ ) # random is a generalised function for letters, characters and numbers def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' return "".join(secrets.choice(lowerCamelCase__ ) for _ in range(lowerCamelCase__ ) ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' pass # Put your code here... def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' pass # Put your code here... def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' pass # Put your code here... def A ( _lowerCamelCase , _lowerCamelCase = 8 ): '''simple docstring''' if len(lowerCamelCase__ ) < min_length: # Your Password must be at least 8 characters long return False _lowerCAmelCase : List[Any] = any(char in ascii_uppercase for char in password ) _lowerCAmelCase : Tuple = any(char in ascii_lowercase for char in password ) _lowerCAmelCase : Union[str, Any] = any(char in digits for char in password ) _lowerCAmelCase : Dict = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def A ( ): '''simple docstring''' _lowerCAmelCase : Optional[int] = int(input("Please indicate the max length of your password: " ).strip() ) _lowerCAmelCase : List[str] = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:" , password_generator(lowerCamelCase__ ) ) print( "Alternative Password generated:" , alternative_password_generator(lowerCamelCase__ , lowerCamelCase__ ) , ) print("[If you are thinking of using this passsword, You better save it.]" ) if __name__ == "__main__": main()
354
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class UpperCAmelCase_ ( a): lowerCamelCase__ = 42 lowerCamelCase__ = 42 class UpperCAmelCase_ ( a , a): lowerCamelCase__ = 1 @register_to_config def __init__( self, __a = 2000, __a = 0.15, __a = 0.01, __a = 1_348.0, __a = 1E-5, __a = 1, ): '''simple docstring''' _lowerCAmelCase : Dict = sigma_max # setable values _lowerCAmelCase : str = None self.set_sigmas(__a, __a, __a, __a) def snake_case__ ( self, __a, __a = None): '''simple docstring''' return sample def snake_case__ ( self, __a, __a = None, __a = None): '''simple docstring''' _lowerCAmelCase : int = sampling_eps if sampling_eps is not None else self.config.sampling_eps _lowerCAmelCase : Dict = torch.linspace(1, __a, __a, device=__a) def snake_case__ ( self, __a, __a = None, __a = None, __a = None): '''simple docstring''' _lowerCAmelCase : List[str] = sigma_min if sigma_min is not None else self.config.sigma_min _lowerCAmelCase : Tuple = sigma_max if sigma_max is not None else self.config.sigma_max _lowerCAmelCase : str = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(__a, __a) _lowerCAmelCase : int = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) _lowerCAmelCase : Any = torch.exp(torch.linspace(math.log(__a), math.log(__a), __a)) _lowerCAmelCase : int = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps]) def snake_case__ ( self, __a, __a): '''simple docstring''' return torch.where( timesteps == 0, torch.zeros_like(t.to(timesteps.device)), self.discrete_sigmas[timesteps - 1].to(timesteps.device), ) def snake_case__ ( self, __a, __a, __a, __a = None, __a = True, ): '''simple docstring''' if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler") _lowerCAmelCase : Dict = timestep * torch.ones( sample.shape[0], device=sample.device) # torch.repeat_interleave(timestep, sample.shape[0]) _lowerCAmelCase : Dict = (timestep * (len(self.timesteps) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda _lowerCAmelCase : Union[str, Any] = timesteps.to(self.discrete_sigmas.device) _lowerCAmelCase : Any = self.discrete_sigmas[timesteps].to(sample.device) _lowerCAmelCase : List[Any] = self.get_adjacent_sigma(__a, __a).to(sample.device) _lowerCAmelCase : List[str] = torch.zeros_like(__a) _lowerCAmelCase : Union[str, Any] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods _lowerCAmelCase : Union[str, Any] = diffusion.flatten() while len(diffusion.shape) < len(sample.shape): _lowerCAmelCase : Optional[int] = diffusion.unsqueeze(-1) _lowerCAmelCase : Dict = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of _lowerCAmelCase : Optional[Any] = randn_tensor( sample.shape, layout=sample.layout, generator=__a, device=sample.device, dtype=sample.dtype) _lowerCAmelCase : int = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? _lowerCAmelCase : Tuple = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=__a, prev_sample_mean=__a) def snake_case__ ( self, __a, __a, __a = None, __a = True, ): '''simple docstring''' if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler") # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction _lowerCAmelCase : Union[str, Any] = randn_tensor(sample.shape, layout=sample.layout, generator=__a).to(sample.device) # compute step size from the model_output, the noise, and the snr _lowerCAmelCase : Any = torch.norm(model_output.reshape(model_output.shape[0], -1), dim=-1).mean() _lowerCAmelCase : Dict = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean() _lowerCAmelCase : Optional[Any] = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 _lowerCAmelCase : Dict = step_size * torch.ones(sample.shape[0]).to(sample.device) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term _lowerCAmelCase : List[Any] = step_size.flatten() while len(step_size.shape) < len(sample.shape): _lowerCAmelCase : int = step_size.unsqueeze(-1) _lowerCAmelCase : List[Any] = sample + step_size * model_output _lowerCAmelCase : Tuple = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a) def snake_case__ ( self, __a, __a, __a, ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = timesteps.to(original_samples.device) _lowerCAmelCase : Union[str, Any] = self.discrete_sigmas.to(original_samples.device)[timesteps] _lowerCAmelCase : Any = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(__a) * sigmas[:, None, None, None] ) _lowerCAmelCase : int = noise + original_samples return noisy_samples def __len__( self): '''simple docstring''' return self.config.num_train_timesteps
300
0
"""simple docstring""" def lowercase (_lowerCAmelCase = 50 ): __lowerCAmelCase = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F"{solution() = }")
301
"""simple docstring""" import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE_ = '''bart''' SCREAMING_SNAKE_CASE_ = True @st.cache(allow_output_mutation=_lowerCAmelCase ) def lowercase (): if LOAD_DENSE_INDEX: __lowerCAmelCase = AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased""" ) __lowerCAmelCase = AutoModel.from_pretrained("""yjernite/retribert-base-uncased""" ).to("""cuda:0""" ) __lowerCAmelCase = qar_model.eval() else: __lowerCAmelCase , __lowerCAmelCase = (None, None) if MODEL_TYPE == "bart": __lowerCAmelCase = AutoTokenizer.from_pretrained("""yjernite/bart_eli5""" ) __lowerCAmelCase = AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5""" ).to("""cuda:0""" ) __lowerCAmelCase = torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth""" ) sas_model.load_state_dict(save_dict["""model"""] ) __lowerCAmelCase = sas_model.eval() else: __lowerCAmelCase , __lowerCAmelCase = make_qa_sas_model( model_name="""t5-small""" , from_file="""seq2seq_models/eli5_t5_model_1024_4.pth""" , device="""cuda:0""" ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=_lowerCAmelCase ) def lowercase (): if LOAD_DENSE_INDEX: __lowerCAmelCase = faiss.StandardGpuResources() __lowerCAmelCase = datasets.load_dataset(path="""wiki_snippets""" , name="""wiki40b_en_100_0""" )["""train"""] __lowerCAmelCase = np.memmap( """wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat""" , dtype="""float32""" , mode="""r""" , shape=(wikiaab_passages.num_rows, 128) , ) __lowerCAmelCase = faiss.IndexFlatIP(128 ) __lowerCAmelCase = faiss.index_cpu_to_gpu(_lowerCAmelCase , 1 , _lowerCAmelCase ) wikiaab_gpu_index_flat.add(_lowerCAmelCase ) # TODO fix for larger GPU else: __lowerCAmelCase , __lowerCAmelCase = (None, None) __lowerCAmelCase = Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=_lowerCAmelCase ) def lowercase (): __lowerCAmelCase = datasets.load_dataset("""eli5""" , name="""LFQA_reddit""" ) __lowerCAmelCase = elia["""train_eli5"""] __lowerCAmelCase = np.memmap( """eli5_questions_reps.dat""" , dtype="""float32""" , mode="""r""" , shape=(elia_train.num_rows, 128) ) __lowerCAmelCase = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(_lowerCAmelCase ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = load_indexes() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = load_models() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = load_train_data() def lowercase (_lowerCAmelCase , _lowerCAmelCase=10 ): __lowerCAmelCase = embed_questions_for_retrieval([question] , _lowerCAmelCase , _lowerCAmelCase ) __lowerCAmelCase , __lowerCAmelCase = eli5_train_q_index.search(_lowerCAmelCase , _lowerCAmelCase ) __lowerCAmelCase = [elia_train[int(_lowerCAmelCase )] for i in I[0]] return nn_examples def lowercase (_lowerCAmelCase , _lowerCAmelCase="wiki40b" , _lowerCAmelCase="dense" , _lowerCAmelCase=10 ): if source == "none": __lowerCAmelCase , __lowerCAmelCase = (""" <P> """.join(["""""" for _ in range(11 )] ).strip(), []) else: if method == "dense": __lowerCAmelCase , __lowerCAmelCase = query_qa_dense_index( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) else: __lowerCAmelCase , __lowerCAmelCase = query_es_index( _lowerCAmelCase , _lowerCAmelCase , index_name="""english_wiki40b_snippets_100w""" , n_results=_lowerCAmelCase , ) __lowerCAmelCase = [ (res["""article_title"""], res["""section_title"""].strip(), res["""score"""], res["""passage_text"""]) for res in hit_lst ] __lowerCAmelCase = """question: {} context: {}""".format(_lowerCAmelCase , _lowerCAmelCase ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda _lowerCAmelCase : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowerCAmelCase : None), } ) def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=64 , _lowerCAmelCase=256 , _lowerCAmelCase=False , _lowerCAmelCase=2 , _lowerCAmelCase=0.95 , _lowerCAmelCase=0.8 ): with torch.no_grad(): __lowerCAmelCase = qa_sas_generate( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , num_answers=1 , num_beams=_lowerCAmelCase , min_len=_lowerCAmelCase , max_len=_lowerCAmelCase , do_sample=_lowerCAmelCase , temp=_lowerCAmelCase , top_p=_lowerCAmelCase , top_k=_lowerCAmelCase , max_input_length=1024 , device="""cuda:0""" , )[0] return (answer, support_list) st.title('''Long Form Question Answering with ELI5''') # Start sidebar SCREAMING_SNAKE_CASE_ = '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>''' SCREAMING_SNAKE_CASE_ = ''' <html> <head> <style> .img-container { padding-left: 90px; padding-right: 90px; padding-top: 50px; padding-bottom: 50px; background-color: #f0f3f9; } </style> </head> <body> <span class="img-container"> <!-- Inline parent element --> %s </span> </body> </html> ''' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE_ = ''' This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html). First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset, a pre-processed fixed snapshot of Wikipedia. ''' st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE_ = [ '''Answer the question''', '''View the retrieved document only''', '''View the most similar ELI5 question and answer''', '''Show me everything, please!''', ] SCREAMING_SNAKE_CASE_ = st.sidebar.checkbox('''Demo options''') if demo_options: SCREAMING_SNAKE_CASE_ = st.sidebar.selectbox( '''''', action_list, index=3, ) SCREAMING_SNAKE_CASE_ = action_list.index(action_st) SCREAMING_SNAKE_CASE_ = st.sidebar.selectbox( '''''', ['''Show full text of passages''', '''Show passage section titles'''], index=0, ) SCREAMING_SNAKE_CASE_ = show_type == '''Show full text of passages''' else: SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = st.sidebar.checkbox('''Retrieval options''') if retrieval_options: SCREAMING_SNAKE_CASE_ = ''' ### Information retriever options The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs. The answer is then generated by sequence to sequence model which takes the question and retrieved document as input. ''' st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE_ = st.sidebar.selectbox('''Which Wikipedia format should the model use?''', ['''wiki40b''', '''none''']) SCREAMING_SNAKE_CASE_ = st.sidebar.selectbox('''Which Wikipedia indexer should the model use?''', ['''dense''', '''sparse''', '''mixed''']) else: SCREAMING_SNAKE_CASE_ = '''wiki40b''' SCREAMING_SNAKE_CASE_ = '''dense''' SCREAMING_SNAKE_CASE_ = '''beam''' SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 64 SCREAMING_SNAKE_CASE_ = 256 SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = st.sidebar.checkbox('''Generation options''') if generate_options: SCREAMING_SNAKE_CASE_ = ''' ### Answer generation options The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large) weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with **beam** search, or **sample** from the decoder\'s output probabilities. ''' st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE_ = st.sidebar.selectbox('''Would you like to use beam search or sample an answer?''', ['''beam''', '''sampled''']) SCREAMING_SNAKE_CASE_ = st.sidebar.slider( '''Minimum generation length''', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE_ = st.sidebar.slider( '''Maximum generation length''', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE_ = st.sidebar.slider('''Beam size''', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE_ = st.sidebar.slider( '''Nucleus sampling p''', min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE_ = st.sidebar.slider( '''Temperature''', min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE_ = None # start main text SCREAMING_SNAKE_CASE_ = [ '''<MY QUESTION>''', '''How do people make chocolate?''', '''Why do we get a fever when we are sick?''', '''How can different animals perceive different colors?''', '''What is natural language processing?''', '''What\'s the best way to treat a sunburn?''', '''What exactly are vitamins ?''', '''How does nuclear energy provide electricity?''', '''What\'s the difference between viruses and bacteria?''', '''Why are flutes classified as woodwinds when most of them are made out of metal ?''', '''Why do people like drinking coffee even though it tastes so bad?''', '''What happens when wine ages? How does it make the wine taste better?''', '''If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?''', '''How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?''', '''How does New Zealand have so many large bird predators?''', ] SCREAMING_SNAKE_CASE_ = st.selectbox( '''What would you like to ask? ---- select <MY QUESTION> to enter a new query''', questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE_ = st.text_input('''Enter your question here:''', '''''') else: SCREAMING_SNAKE_CASE_ = question_s if st.button('''Show me!'''): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = make_support(question, source=wiki_source, method='''dense''', n_results=10) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = make_support(question, source=wiki_source, method='''sparse''', n_results=10) SCREAMING_SNAKE_CASE_ = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE_ = support_list[:10] SCREAMING_SNAKE_CASE_ = '''<P> ''' + ''' <P> '''.join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == '''sampled'''), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('''### The model generated answer is:''') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('''--- \n ### The model is drawing information from the following Wikipedia passages:''') for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE_ = '''https://en.wikipedia.org/wiki/{}'''.format(res[0].replace(''' ''', '''_''')) SCREAMING_SNAKE_CASE_ = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE_ = '''[{}]({})'''.format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE_ = sec_titles.split(''' & ''') SCREAMING_SNAKE_CASE_ = ''' & '''.join( ['''[{}]({}#{})'''.format(sec.strip(), wiki_url, sec.strip().replace(''' ''', '''_''')) for sec in sec_list] ) st.markdown( '''{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'''.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '''> <span style="font-family:arial; font-size:10pt;">''' + res[-1] + '''</span>''', unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE_ = find_nearest_training(question) SCREAMING_SNAKE_CASE_ = nn_train_list[0] st.markdown( '''--- \n ### The most similar question in the ELI5 training set was: \n\n {}'''.format(train_exple['''title''']) ) SCREAMING_SNAKE_CASE_ = [ '''{}. {}'''.format(i + 1, ''' \n'''.join([line.strip() for line in ans.split('''\n''') if line.strip() != ''''''])) for i, (ans, sc) in enumerate(zip(train_exple['''answers''']['''text'''], train_exple['''answers''']['''score'''])) if i == 0 or sc > 2 ] st.markdown('''##### Its answers were: \n\n {}'''.format('''\n'''.join(answers_st))) SCREAMING_SNAKE_CASE_ = ''' --- **Disclaimer** *The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system. Evaluating biases of such a model and ensuring factual generations are still very much open research problems. Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.* ''' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
301
1
from collections import deque from .hash_table import HashTable class a_ ( _snake_case ): def __init__( self :Union[str, Any] , *_lowercase :Optional[int] , **_lowercase :List[str]) -> int: super().__init__(*_lowercase , **_lowercase) def __a ( self :Optional[int] , _lowercase :str , _lowercase :Optional[Any]) -> List[str]: UpperCAmelCase_ = deque([]) if self.values[key] is None else self.values[key] self.values[key].appendleft(_lowercase) UpperCAmelCase_ = self.values[key] def __a ( self :Optional[Any]) -> List[Any]: return ( sum(self.charge_factor - len(_lowercase) for slot in self.values) / self.size_table * self.charge_factor ) def __a ( self :Any , _lowercase :Union[str, Any] , _lowercase :int=None) -> Tuple: if not ( len(self.values[key]) == self.charge_factor and self.values.count(_lowercase) == 0 ): return key return super()._collision_resolution(_lowercase , _lowercase)
356
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase_ = {"configuration_opt": ["OPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OPTConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ "OPT_PRETRAINED_MODEL_ARCHIVE_LIST", "OPTForCausalLM", "OPTModel", "OPTPreTrainedModel", "OPTForSequenceClassification", "OPTForQuestionAnswering", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = ["TFOPTForCausalLM", "TFOPTModel", "TFOPTPreTrainedModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ "FlaxOPTForCausalLM", "FlaxOPTModel", "FlaxOPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
344
0