code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'BridgeTower/bridgetower-base': 'https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json', 'BridgeTower/bridgetower-base-itm-mlm': ( 'https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "bridgetower_vision_model" def __init__( self : str , A__ : List[str]=7_6_8 , A__ : List[str]=1_2 , A__ : Optional[Any]=3 , A__ : Optional[Any]=1_6 , A__ : Dict=2_8_8 , A__ : str=1 , A__ : Dict=1E-05 , A__ : Optional[Any]=False , A__ : List[str]=True , A__ : List[str]=False , **A__ : List[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = hidden_size a__ : Union[str, Any] = num_hidden_layers a__ : str = num_channels a__ : Optional[int] = patch_size a__ : Union[str, Any] = image_size a__ : Union[str, Any] = initializer_factor a__ : Dict = layer_norm_eps a__ : Any = stop_gradient a__ : Optional[Any] = share_layernorm a__ : Optional[int] = remove_last_layer @classmethod def __lowerCAmelCase ( cls : Union[str, Any] , A__ : Union[str, os.PathLike] , **A__ : int ) -> "PretrainedConfig": '''simple docstring''' a__ , a__ : Optional[int] = cls.get_config_dict(A__ , **A__ ) if config_dict.get('''model_type''' ) == "bridgetower": a__ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A__ , **A__ ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "bridgetower_text_model" def __init__( self : Optional[int] , A__ : Dict=5_0_2_6_5 , A__ : Optional[Any]=7_6_8 , A__ : List[str]=1_2 , A__ : int=1_2 , A__ : Dict=1 , A__ : List[str]=3_0_7_2 , A__ : List[str]="gelu" , A__ : Any=0.1 , A__ : Any=0.1 , A__ : Optional[int]=5_1_4 , A__ : Union[str, Any]=1 , A__ : List[Any]=1E-05 , A__ : Optional[Any]=1 , A__ : str=0 , A__ : Tuple=2 , A__ : str="absolute" , A__ : List[str]=True , **A__ : Optional[int] , ) -> Tuple: '''simple docstring''' super().__init__(**A__ ) a__ : Optional[Any] = vocab_size a__ : int = hidden_size a__ : Any = num_hidden_layers a__ : Optional[int] = num_attention_heads a__ : Union[str, Any] = hidden_act a__ : Optional[int] = initializer_factor a__ : Optional[int] = intermediate_size a__ : str = hidden_dropout_prob a__ : Tuple = attention_probs_dropout_prob a__ : Any = max_position_embeddings a__ : Dict = type_vocab_size a__ : str = layer_norm_eps a__ : Union[str, Any] = position_embedding_type a__ : Tuple = use_cache a__ : List[str] = pad_token_id a__ : int = bos_token_id a__ : Union[str, Any] = eos_token_id @classmethod def __lowerCAmelCase ( cls : List[Any] , A__ : Union[str, os.PathLike] , **A__ : Dict ) -> "PretrainedConfig": '''simple docstring''' a__ , a__ : str = cls.get_config_dict(A__ , **A__ ) if config_dict.get('''model_type''' ) == "bridgetower": a__ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A__ , **A__ ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "bridgetower" def __init__( self : Tuple , A__ : List[str]=True , A__ : List[Any]="gelu" , A__ : int=7_6_8 , A__ : Tuple=1 , A__ : Optional[Any]=1E-05 , A__ : Optional[Any]=False , A__ : List[str]="add" , A__ : int=1_2 , A__ : Tuple=6 , A__ : str=False , A__ : Optional[int]=False , A__ : Tuple=None , A__ : Tuple=None , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : int = kwargs.pop('''text_config_dict''' , A__ ) a__ : List[str] = kwargs.pop('''vision_config_dict''' , A__ ) super().__init__(**A__ ) a__ : List[Any] = share_cross_modal_transformer_layers a__ : Optional[Any] = hidden_act a__ : Tuple = hidden_size a__ : Any = initializer_factor a__ : str = layer_norm_eps a__ : Dict = share_link_tower_layers a__ : List[str] = link_tower_type a__ : Any = num_attention_heads a__ : Dict = num_hidden_layers a__ : int = tie_word_embeddings a__ : str = init_layernorm_from_vision_encoder if text_config is None: a__ : List[Any] = {} logger.info('''`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.''' ) if vision_config is None: a__ : List[Any] = {} logger.info('''`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.''' ) a__ : Optional[int] = BridgeTowerTextConfig(**A__ ) a__ : Tuple = BridgeTowerVisionConfig(**A__ ) @classmethod def __lowerCAmelCase ( cls : List[Any] , A__ : BridgeTowerTextConfig , A__ : BridgeTowerVisionConfig , **A__ : Any ) -> Dict: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A__ ) def __lowerCAmelCase ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' a__ : int = copy.deepcopy(self.__dict__ ) a__ : Any = self.text_config.to_dict() a__ : Tuple = self.vision_config.to_dict() a__ : Dict = self.__class__.model_type return output
688
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : 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 : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
1
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : """simple docstring""" def __init__( self : Union[str, Any] , A__ : str , A__ : int=1_3 , A__ : int=7 , A__ : Dict=True , A__ : Optional[int]=True , A__ : Tuple=True , A__ : Dict=True , A__ : List[Any]=9_9 , A__ : str=1_6 , A__ : Union[str, Any]=3_6 , A__ : Tuple=6 , A__ : List[str]=6 , A__ : Optional[Any]=6 , A__ : str=3_7 , A__ : Tuple="gelu" , A__ : Dict=0.1 , A__ : int=0.1 , A__ : Optional[int]=5_1_2 , A__ : Union[str, Any]=1_6 , A__ : Dict=2 , A__ : int=0.02 , A__ : Optional[Any]=3 , A__ : Optional[Any]=4 , A__ : List[Any]=None , ) -> List[str]: '''simple docstring''' a__ : Tuple = parent a__ : int = batch_size a__ : Dict = seq_length a__ : Dict = is_training a__ : Optional[Any] = use_input_mask a__ : Tuple = use_token_type_ids a__ : Optional[Any] = use_labels a__ : Optional[int] = vocab_size a__ : int = embedding_size a__ : str = hidden_size a__ : Optional[int] = num_hidden_layers a__ : Dict = num_hidden_groups a__ : Union[str, Any] = num_attention_heads a__ : str = intermediate_size a__ : Tuple = hidden_act a__ : Optional[int] = hidden_dropout_prob a__ : str = attention_probs_dropout_prob a__ : List[str] = max_position_embeddings a__ : Optional[int] = type_vocab_size a__ : List[str] = type_sequence_label_size a__ : Any = initializer_range a__ : str = num_labels a__ : Optional[Any] = num_choices a__ : Optional[int] = scope def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' a__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Any = None if self.use_input_mask: a__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a__ : List[Any] = None if self.use_token_type_ids: a__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : Tuple = None a__ : List[Any] = None a__ : List[Any] = None if self.use_labels: a__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : str = ids_tensor([self.batch_size] , self.num_choices ) a__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : int ) -> Optional[Any]: '''simple docstring''' return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def __lowerCAmelCase ( self : int , A__ : Optional[Any] , A__ : Tuple , A__ : Any , A__ : List[str] , A__ : List[Any] , A__ : Dict , A__ : Dict ) -> List[str]: '''simple docstring''' a__ : Any = AlbertModel(config=A__ ) model.to(A__ ) model.eval() a__ : Tuple = model(A__ , attention_mask=A__ , token_type_ids=A__ ) a__ : str = model(A__ , token_type_ids=A__ ) a__ : List[Any] = model(A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCAmelCase ( self : List[str] , A__ : Dict , A__ : int , A__ : int , A__ : Optional[Any] , A__ : Any , A__ : Tuple , A__ : str ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] = AlbertForPreTraining(config=A__ ) model.to(A__ ) model.eval() a__ : str = model( A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ , sentence_order_label=A__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Dict , A__ : int , A__ : List[str] , A__ : Dict , A__ : int , A__ : List[str] , A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' a__ : List[str] = AlbertForMaskedLM(config=A__ ) model.to(A__ ) model.eval() a__ : Dict = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[Any] , A__ : List[Any] , A__ : Optional[Any] , A__ : List[str] , A__ : Optional[int] , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' a__ : Union[str, Any] = AlbertForQuestionAnswering(config=A__ ) model.to(A__ ) model.eval() a__ : Dict = model( A__ , attention_mask=A__ , token_type_ids=A__ , start_positions=A__ , end_positions=A__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self : Dict , A__ : Optional[int] , A__ : Optional[int] , A__ : Dict , A__ : str , A__ : int , A__ : Union[str, Any] , A__ : Any ) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] = self.num_labels a__ : List[Any] = AlbertForSequenceClassification(A__ ) model.to(A__ ) model.eval() a__ : List[str] = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : int , A__ : List[Any] , A__ : Dict , A__ : str , A__ : Any , A__ : Union[str, Any] , A__ : List[str] , A__ : Optional[Any] ) -> str: '''simple docstring''' a__ : List[str] = self.num_labels a__ : Optional[int] = AlbertForTokenClassification(config=A__ ) model.to(A__ ) model.eval() a__ : Dict = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : Dict , A__ : List[Any] , A__ : List[str] , A__ : int , A__ : Union[str, Any] , A__ : str , A__ : Optional[Any] , A__ : List[str] ) -> List[Any]: '''simple docstring''' a__ : List[Any] = self.num_choices a__ : Optional[Any] = AlbertForMultipleChoice(config=A__ ) model.to(A__ ) model.eval() a__ : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Optional[Any] = model( A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : Tuple ) -> List[Any]: '''simple docstring''' a__ : int = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : Optional[Any] = config_and_inputs a__ : Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": AlbertModel, "fill-mask": AlbertForMaskedLM, "question-answering": AlbertForQuestionAnswering, "text-classification": AlbertForSequenceClassification, "token-classification": AlbertForTokenClassification, "zero-shot": AlbertForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = True def __lowerCAmelCase ( self : str , A__ : Union[str, Any] , A__ : List[str] , A__ : str=False ) -> Optional[int]: '''simple docstring''' a__ : List[str] = super()._prepare_for_class(A__ , A__ , return_labels=A__ ) if return_labels: if model_class in get_values(A__ ): a__ : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=A__ ) a__ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A__ ) return inputs_dict def __lowerCAmelCase ( self : Tuple ) -> str: '''simple docstring''' a__ : Tuple = AlbertModelTester(self ) a__ : str = ConfigTester(self , config_class=A__ , hidden_size=3_7 ) def __lowerCAmelCase ( self : Union[str, Any] ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def __lowerCAmelCase ( self : List[Any] ) -> Any: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) def __lowerCAmelCase ( self : Any ) -> Any: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*A__ ) def __lowerCAmelCase ( self : Optional[Any] ) -> Any: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A__ ) def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' a__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A__ ) def __lowerCAmelCase ( self : Dict ) -> Union[str, Any]: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A__ ) def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A__ ) def __lowerCAmelCase ( self : Tuple ) -> int: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a__ : Tuple = type self.model_tester.create_and_check_model(*A__ ) @slow def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : int = AlbertModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' a__ : Union[str, Any] = AlbertModel.from_pretrained('''albert-base-v2''' ) a__ : Optional[Any] = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) a__ : Optional[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): a__ : Any = model(A__ , attention_mask=A__ )[0] a__ : str = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , A__ ) a__ : Any = 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] , A__ , atol=1E-4 ) )
688
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : Any ): a__ : List[Any] = len(lowerCAmelCase__ ) while cur > 1: # Find the maximum number in arr a__ : Optional[Any] = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi a__ : Union[str, Any] = arr[mi::-1] + arr[mi + 1 : len(lowerCAmelCase__ )] # Reverse whole list a__ : Tuple = arr[cur - 1 :: -1] + arr[cur : len(lowerCAmelCase__ )] cur -= 1 return arr if __name__ == "__main__": __SCREAMING_SNAKE_CASE = input('Enter numbers separated by a comma:\n').strip() __SCREAMING_SNAKE_CASE = [int(item) for item in user_input.split(',')] print(pancake_sort(unsorted))
688
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __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 a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
1
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
1
'''simple docstring''' import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) def __a ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] ): # save results if os.path.exists(lowerCAmelCase__ ): if os.path.exists(os.path.join(lowerCAmelCase__ , '''config.json''' ) ) and os.path.isfile( os.path.join(lowerCAmelCase__ , '''config.json''' ) ): os.remove(os.path.join(lowerCAmelCase__ , '''config.json''' ) ) if os.path.exists(os.path.join(lowerCAmelCase__ , '''pytorch_model.bin''' ) ) and os.path.isfile( os.path.join(lowerCAmelCase__ , '''pytorch_model.bin''' ) ): os.remove(os.path.join(lowerCAmelCase__ , '''pytorch_model.bin''' ) ) else: os.makedirs(lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any=False ): a__ : Union[str, Any] = 2 if unlogit: a__ : Union[str, Any] = torch.pow(lowerCAmelCase__ , lowerCAmelCase__ ) a__ : Optional[int] = p * torch.log(lowerCAmelCase__ ) a__ : Union[str, Any] = 0 return -plogp.sum(dim=-1 ) def __a ( lowerCAmelCase__ : str ): logger.info('''lv, h >\t''' + '''\t'''.join(F'{x + 1}' for x in range(len(lowerCAmelCase__ ) ) ) ) for row in range(len(lowerCAmelCase__ ) ): if tensor.dtype != torch.long: logger.info(F'layer {row + 1}:\t' + '''\t'''.join(F'{x:.5f}' for x in tensor[row].cpu().data ) ) else: logger.info(F'layer {row + 1}:\t' + '''\t'''.join(F'{x:d}' for x in tensor[row].cpu().data ) ) def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Tuple=True , lowerCAmelCase__ : Dict=True , lowerCAmelCase__ : int=None , lowerCAmelCase__ : Any=False ): a__ , a__ : Tuple = model.config.num_hidden_layers, model.config.num_attention_heads a__ : Optional[Any] = torch.zeros(lowerCAmelCase__ , lowerCAmelCase__ ).to(args.device ) a__ : Tuple = torch.zeros(lowerCAmelCase__ , lowerCAmelCase__ ).to(args.device ) if head_mask is None: a__ : Union[str, Any] = torch.ones(lowerCAmelCase__ , lowerCAmelCase__ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCAmelCase__ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: a__ : Dict = None a__ : Optional[Any] = 0.0 a__ : List[Any] = 0.0 for step, inputs in enumerate(tqdm(lowerCAmelCase__ , desc='''Iteration''' , disable=args.local_rank not in [-1, 0] ) ): a__ : Any = tuple(t.to(args.device ) for t in inputs ) ((a__) , ) : Any = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) a__ : List[str] = model(lowerCAmelCase__ , labels=lowerCAmelCase__ , head_mask=lowerCAmelCase__ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) a__ , a__ , a__ : Any = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCAmelCase__ ): a__ : Optional[int] = entropy(attn.detach() , lowerCAmelCase__ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCAmelCase__ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: a__ : Any = 2 a__ : List[Any] = torch.pow(torch.pow(lowerCAmelCase__ , lowerCAmelCase__ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1E-20 if not args.dont_normalize_global_importance: a__ : str = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('''Attention entropies''' ) print_ad_tensor(lowerCAmelCase__ ) if compute_importance: logger.info('''Head importance scores''' ) print_ad_tensor(lowerCAmelCase__ ) logger.info('''Head ranked by importance scores''' ) a__ : int = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) a__ : Union[str, Any] = torch.arange( head_importance.numel() , device=args.device ) a__ : Any = head_ranks.view_as(lowerCAmelCase__ ) print_ad_tensor(lowerCAmelCase__ ) return attn_entropy, head_importance, total_loss def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ , a__ , a__ : int = compute_heads_importance(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , compute_entropy=lowerCAmelCase__ ) a__ : Any = 1 / loss # instead of downsteam score use the LM loss logger.info('''Pruning: original score: %f, threshold: %f''' , lowerCAmelCase__ , original_score * args.masking_threshold ) a__ : int = torch.ones_like(lowerCAmelCase__ ) a__ : Dict = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) a__ : List[str] = original_score while current_score >= original_score * args.masking_threshold: a__ : int = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads a__ : Union[str, Any] = float('''Inf''' ) a__ : int = head_importance.view(-1 ).sort()[1] if len(lowerCAmelCase__ ) <= num_to_mask: print('''BREAK BY num_to_mask''' ) break # mask heads a__ : Optional[Any] = current_heads_to_mask[:num_to_mask] logger.info('''Heads to mask: %s''' , str(current_heads_to_mask.tolist() ) ) a__ : Union[str, Any] = new_head_mask.view(-1 ) a__ : Tuple = 0.0 a__ : Any = new_head_mask.view_as(lowerCAmelCase__ ) a__ : Dict = new_head_mask.clone().detach() print_ad_tensor(lowerCAmelCase__ ) # Compute metric and head importance again a__ , a__ , a__ : int = compute_heads_importance( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , compute_entropy=lowerCAmelCase__ , head_mask=lowerCAmelCase__ ) a__ : List[Any] = 1 / loss logger.info( '''Masking: current score: %f, remaining heads %d (%.1f percents)''' , lowerCAmelCase__ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('''Final head mask''' ) print_ad_tensor(lowerCAmelCase__ ) np.save(os.path.join(args.output_dir , '''head_mask.npy''' ) , head_mask.detach().cpu().numpy() ) return head_mask def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str] ): a__ : str = datetime.now() a__ , a__ , a__ : Optional[int] = compute_heads_importance( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , compute_entropy=lowerCAmelCase__ , compute_importance=lowerCAmelCase__ , head_mask=lowerCAmelCase__ ) a__ : List[Any] = 1 / loss a__ : Optional[int] = datetime.now() - before_time a__ : Tuple = sum(p.numel() for p in model.parameters() ) a__ : Optional[int] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCAmelCase__ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : str = [ v, ] assert sum(len(lowerCAmelCase__ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCAmelCase__ ) a__ : int = sum(p.numel() for p in model.parameters() ) a__ : Optional[int] = datetime.now() a__ , a__ , a__ : List[Any] = compute_heads_importance( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , compute_entropy=lowerCAmelCase__ , compute_importance=lowerCAmelCase__ , head_mask=lowerCAmelCase__ , actually_pruned=lowerCAmelCase__ , ) a__ : List[str] = 1 / loss a__ : Dict = datetime.now() - before_time logger.info( '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)''' , lowerCAmelCase__ , lowerCAmelCase__ , pruned_num_params / original_num_params * 100 , ) logger.info('''Pruning: score with masking: %f score with pruning: %f''' , lowerCAmelCase__ , lowerCAmelCase__ ) logger.info('''Pruning: speed ratio (original timing / new timing): %f percents''' , original_time / new_time * 100 ) save_model(lowerCAmelCase__ , args.output_dir ) def __a ( ): a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--data_dir''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''The input data dir. Should contain the .tsv files (or other data files) for the task.''' , ) parser.add_argument( '''--model_name_or_path''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to pretrained model or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--output_dir''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''The output directory where the model predictions and checkpoints will be written.''' , ) # Other parameters parser.add_argument( '''--config_name''' , default='''''' , type=lowerCAmelCase__ , help='''Pretrained config name or path if not the same as model_name_or_path''' , ) parser.add_argument( '''--tokenizer_name''' , default='''''' , type=lowerCAmelCase__ , help='''Pretrained tokenizer name or path if not the same as model_name_or_path''' , ) parser.add_argument( '''--cache_dir''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , help='''Where do you want to store the pre-trained models downloaded from s3''' , ) parser.add_argument( '''--data_subset''' , type=lowerCAmelCase__ , default=-1 , help='''If > 0: limit the data to a subset of data_subset instances.''' ) parser.add_argument( '''--overwrite_output_dir''' , action='''store_true''' , help='''Whether to overwrite data in output directory''' ) parser.add_argument( '''--overwrite_cache''' , action='''store_true''' , help='''Overwrite the cached training and evaluation sets''' ) parser.add_argument( '''--dont_normalize_importance_by_layer''' , action='''store_true''' , help='''Don\'t normalize importance score by layers''' ) parser.add_argument( '''--dont_normalize_global_importance''' , action='''store_true''' , help='''Don\'t normalize all importance scores between 0 and 1''' , ) parser.add_argument( '''--try_masking''' , action='''store_true''' , help='''Whether to try to mask head until a threshold of accuracy.''' ) parser.add_argument( '''--masking_threshold''' , default=0.9 , type=lowerCAmelCase__ , help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).''' , ) parser.add_argument( '''--masking_amount''' , default=0.1 , type=lowerCAmelCase__ , help='''Amount to heads to masking at each masking step.''' ) parser.add_argument('''--metric_name''' , default='''acc''' , type=lowerCAmelCase__ , help='''Metric to use for head masking.''' ) parser.add_argument( '''--max_seq_length''' , default=128 , type=lowerCAmelCase__ , help=( '''The maximum total input sequence length after WordPiece tokenization. \n''' '''Sequences longer than this will be truncated, sequences shorter padded.''' ) , ) parser.add_argument('''--batch_size''' , default=1 , type=lowerCAmelCase__ , help='''Batch size.''' ) parser.add_argument('''--seed''' , type=lowerCAmelCase__ , default=42 ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ , default=-1 , help='''local_rank for distributed training on gpus''' ) parser.add_argument('''--no_cuda''' , action='''store_true''' , help='''Whether not to use CUDA when available''' ) parser.add_argument('''--server_ip''' , type=lowerCAmelCase__ , default='''''' , help='''Can be used for distant debugging.''' ) parser.add_argument('''--server_port''' , type=lowerCAmelCase__ , default='''''' , help='''Can be used for distant debugging.''' ) a__ : List[str] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('''Waiting for debugger attach''' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCAmelCase__ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: a__ : Any = torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu''' ) a__ : Dict = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) a__ : Optional[Any] = torch.device('''cuda''' , args.local_rank ) a__ : Dict = 1 torch.distributed.init_process_group(backend='''nccl''' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) a__ : Tuple = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: a__ : Tuple = nn.parallel.DistributedDataParallel( lowerCAmelCase__ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCAmelCase__ ) elif args.n_gpu > 1: a__ : Optional[Any] = nn.DataParallel(lowerCAmelCase__ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCAmelCase__ ) torch.save(lowerCAmelCase__ , os.path.join(args.output_dir , '''run_args.bin''' ) ) logger.info('''Training/evaluation parameters %s''' , lowerCAmelCase__ ) # Prepare dataset a__ : List[Any] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) a__ : List[Any] = (torch.from_numpy(lowerCAmelCase__ ),) a__ : int = TensorDataset(*lowerCAmelCase__ ) a__ : str = RandomSampler(lowerCAmelCase__ ) a__ : str = DataLoader(lowerCAmelCase__ , sampler=lowerCAmelCase__ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: a__ : int = mask_heads(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) prune_heads(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
688
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
1
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/config.json', # See all XGLM models at https://huggingface.co/models?filter=xglm } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "xglm" __UpperCamelCase = ["past_key_values"] __UpperCamelCase = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : Any , A__ : Tuple=2_5_6_0_0_8 , A__ : Union[str, Any]=2_0_4_8 , A__ : Any=1_0_2_4 , A__ : Tuple=4_0_9_6 , A__ : Dict=2_4 , A__ : Any=1_6 , A__ : Optional[Any]="gelu" , A__ : Optional[int]=0.1 , A__ : str=0.1 , A__ : List[Any]=0.0 , A__ : List[str]=0.0 , A__ : Tuple=0.02 , A__ : Tuple=True , A__ : Tuple=True , A__ : int=2 , A__ : Optional[int]=1 , A__ : Union[str, Any]=0 , A__ : Optional[Any]=2 , **A__ : Tuple , ) -> Any: '''simple docstring''' a__ : str = vocab_size a__ : List[str] = max_position_embeddings a__ : Any = d_model a__ : List[str] = ffn_dim a__ : int = num_layers a__ : List[Any] = attention_heads a__ : Optional[int] = activation_function a__ : Any = dropout a__ : List[Any] = attention_dropout a__ : List[Any] = activation_dropout a__ : Optional[int] = layerdrop a__ : int = init_std a__ : Dict = scale_embedding # scale factor will be sqrt(d_model) if True a__ : List[str] = use_cache super().__init__( pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , decoder_start_token_id=A__ , **A__ , )
688
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
1
'''simple docstring''' import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def __a ( lowerCAmelCase__ : Any ): monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def __a ( lowerCAmelCase__ : List[Any] ): class lowerCAmelCase__ : """simple docstring""" def __init__( self : int , A__ : Dict ) -> Dict: '''simple docstring''' a__ : int = metric_id class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = [MetricMock(lowerCAmelCase_ ) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def __lowerCAmelCase ( self : str ) -> List[str]: '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple ): if "tmp_path" in args: a__ : List[Any] = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase__ , match='''https://huggingface.co/docs/evaluate''' ): func(*lowerCAmelCase__ )
688
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
1
'''simple docstring''' import math def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : str = len(lowerCAmelCase__ ) a__ : Optional[Any] = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) a__ : Any = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: a__ : Any = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: a__ : Tuple = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": __SCREAMING_SNAKE_CASE = input('Enter numbers separated by a comma:\n').strip() __SCREAMING_SNAKE_CASE = [int(item) for item in user_input.split(',')] __SCREAMING_SNAKE_CASE = int(input('Enter the number to be searched:\n')) __SCREAMING_SNAKE_CASE = jump_search(arr, x) if res == -1: print('Number not found!') else: print(f'Number {x} is at index {res}')
688
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
1
'''simple docstring''' import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Tuple , A__ : Dict , A__ : Union[str, Any] , A__ : Any , A__ : int=None ) -> List[str]: '''simple docstring''' super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = None def __lowerCAmelCase ( self : Dict , A__ : int ) -> Dict: '''simple docstring''' logger.info('''initializing retrieval''' ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info('''dist initialized''' ) # needs to be set manually a__ : str = self._infer_socket_ifname() # avoid clash with the NCCL port a__ : int = str(distributed_port + 1 ) a__ : Dict = dist.new_group(ranks=A__ , backend='''gloo''' ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info('''dist not initialized / main''' ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return dist.get_rank(group=self.process_group ) == 0 def __lowerCAmelCase ( self : Optional[int] , A__ : Any , A__ : Union[str, Any] , A__ : List[Any]=torch.floataa ) -> Optional[int]: '''simple docstring''' a__ : int = torch.empty(A__ , dtype=A__ ) dist.scatter(A__ , src=0 , scatter_list=A__ , group=self.process_group ) return target_tensor def __lowerCAmelCase ( self : Optional[int] ) -> Tuple: '''simple docstring''' a__ : Any = psutil.net_if_addrs() # a hacky way to deal with varying network interface names a__ : str = next((addr for addr in addrs if addr.startswith('''e''' )) , A__ ) return ifname def __lowerCAmelCase ( self : Optional[Any] , A__ : np.ndarray , A__ : int ) -> Tuple[np.ndarray, List[dict]]: '''simple docstring''' if not dist.is_initialized(): a__ , a__ : Tuple = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) # distributed training a__ : List[str] = dist.get_world_size(group=self.process_group ) # gather logic a__ : Optional[int] = None if self._is_main(): a__ : int = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(A__ )] dist.gather(torch.tensor(A__ ) , dst=0 , gather_list=A__ , group=self.process_group ) # scatter logic a__ : Optional[Any] = question_hidden_states.shape[0] a__ : Optional[int] = [] a__ : Any = [] if self._is_main(): assert len(A__ ) == world_size a__ , a__ : int = self._main_retrieve(torch.cat(A__ ).numpy() , A__ ) a__ , a__ : Any = torch.tensor(A__ ), torch.tensor(A__ ) a__ : List[str] = self._chunk_tensor(A__ , A__ ) a__ : Optional[int] = self._chunk_tensor(A__ , A__ ) a__ : List[str] = self._scattered(A__ , [n_queries, n_docs] , target_type=torch.intaa ) a__ : Optional[Any] = self._scattered(A__ , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(A__ )
688
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = 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 flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
1
'''simple docstring''' import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) a__ : Tuple = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) a__ : Optional[int] = '''The dog is cute and lives in the garden house''' a__ : int = jnp.array([tokenizer.encode(A__ )] ) a__ : Optional[int] = (1, 1_2, 7_6_8) # batch_size, sequence_length, embedding_vector_dim a__ : List[str] = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) a__ : Dict = model(A__ )['''last_hidden_state'''] self.assertEqual(output.shape , A__ ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , A__ , atol=1E-3 ) )
688
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : int ): if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : List[Any] = F'Input value of [number={number}] must be an integer' raise TypeError(lowerCAmelCase__ ) if number < 1: a__ : Any = F'Input value of [number={number}] must be > 0' raise ValueError(lowerCAmelCase__ ) a__ : List[Any] = 1 for i in range(1 , lowerCAmelCase__ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
688
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
1
'''simple docstring''' from math import isqrt, loga def __a ( lowerCAmelCase__ : int ): a__ : str = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = False return [i for i in range(2 , lowerCAmelCase__ ) if is_prime[i]] def __a ( lowerCAmelCase__ : int = 800800 , lowerCAmelCase__ : int = 800800 ): a__ : Optional[Any] = degree * loga(lowerCAmelCase__ ) a__ : str = int(lowerCAmelCase__ ) a__ : str = calculate_prime_numbers(lowerCAmelCase__ ) a__ : List[Any] = 0 a__ : Tuple = 0 a__ : str = len(lowerCAmelCase__ ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'{solution() = }')
688
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : int = 10**9 ): a__ : Optional[Any] = 1 a__ : str = 2 a__ : Optional[int] = 0 a__ : Tuple = 0 a__ : int = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value a__ : int = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f'{solution() = }')
688
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) 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 __SCREAMING_SNAKE_CASE = 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-pretraining/requirements.txt') __SCREAMING_SNAKE_CASE = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) __SCREAMING_SNAKE_CASE = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = field( default="cifar10" , metadata={"help": "Name of a dataset from the datasets package"} ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "The column name of the images in the files. If not set, will try to use 'image' or 'img'."} , ) __UpperCamelCase = field(default=lowerCAmelCase_ , metadata={"help": "A folder containing the training data."} ) __UpperCamelCase = field(default=lowerCAmelCase_ , metadata={"help": "A folder containing the validation data."} ) __UpperCamelCase = field( default=0.15 , metadata={"help": "Percent to split off of train for validation."} ) __UpperCamelCase = field(default=32 , metadata={"help": "The size of the square patches to use for masking."} ) __UpperCamelCase = field( default=0.6 , metadata={"help": "Percentage of patches to mask."} , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] = {} if self.train_dir is not None: a__ : int = self.train_dir if self.validation_dir is not None: a__ : List[str] = self.validation_dir a__ : Dict = data_files if data_files else None @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a " "checkpoint identifier on the hub. " "Don't set if you want to train a model from scratch." ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(lowerCAmelCase_ )} , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "Override some existing default config settings when a model is trained from scratch. Example: " "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"} , ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field(default=lowerCAmelCase_ , metadata={"help": "Name or path of preprocessor config."} ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "The size (resolution) of each image. If not specified, will use `image_size` of the configuration." ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration." ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "Stride to use for the encoder."} , ) class lowerCAmelCase__ : """simple docstring""" def __init__( self : Any , A__ : List[str]=1_9_2 , A__ : str=3_2 , A__ : int=4 , A__ : Optional[Any]=0.6 ) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] = input_size a__ : List[Any] = mask_patch_size a__ : Optional[Any] = model_patch_size a__ : Dict = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('''Input size must be divisible by mask patch size''' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('''Mask patch size must be divisible by model patch size''' ) a__ : List[str] = self.input_size // self.mask_patch_size a__ : Optional[Any] = self.mask_patch_size // self.model_patch_size a__ : Optional[int] = self.rand_size**2 a__ : Tuple = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self : Dict ) -> Dict: '''simple docstring''' a__ : Tuple = np.random.permutation(self.token_count )[: self.mask_count] a__ : int = np.zeros(self.token_count , dtype=A__ ) a__ : int = 1 a__ : str = mask.reshape((self.rand_size, self.rand_size) ) a__ : Any = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def __a ( lowerCAmelCase__ : str ): a__ : Optional[int] = torch.stack([example['''pixel_values'''] for example in examples] ) a__ : Any = torch.stack([example['''mask'''] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def __a ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. a__ : Optional[Any] = 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. a__ , a__ , a__ : str = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: a__ , a__ , a__ : int = 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_mim''' , lowerCAmelCase__ , lowerCAmelCase__ ) # 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() a__ : Dict = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase__ ) transformers.utils.logging.set_verbosity(lowerCAmelCase__ ) 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. a__ : Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: a__ : int = 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.''' ) # Initialize our dataset. a__ : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. a__ : Union[str, Any] = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , lowerCAmelCase__ ) and data_args.train_val_split > 0.0: a__ : Union[str, Any] = ds['''train'''].train_test_split(data_args.train_val_split ) a__ : List[str] = split['''train'''] a__ : str = split['''test'''] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a__ : Any = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name_or_path: a__ : Tuple = AutoConfig.from_pretrained(model_args.config_name_or_path , **lowerCAmelCase__ ) elif model_args.model_name_or_path: a__ : List[str] = AutoConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) else: a__ : Any = CONFIG_MAPPING[model_args.model_type]() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(lowerCAmelCase__ , '''decoder_type''' ): a__ : Any = '''simmim''' # adapt config a__ : Optional[Any] = model_args.image_size if model_args.image_size is not None else config.image_size a__ : Tuple = model_args.patch_size if model_args.patch_size is not None else config.patch_size a__ : int = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { '''image_size''': model_args.image_size, '''patch_size''': model_args.patch_size, '''encoder_stride''': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: a__ : List[Any] = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **lowerCAmelCase__ ) elif model_args.model_name_or_path: a__ : Optional[int] = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) else: a__ : Any = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } a__ : List[Any] = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: a__ : List[Any] = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=lowerCAmelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) a__ : Optional[int] = AutoModelForMaskedImageModeling.from_config(lowerCAmelCase__ ) if training_args.do_train: a__ : Tuple = ds['''train'''].column_names else: a__ : Optional[int] = ds['''validation'''].column_names if data_args.image_column_name is not None: a__ : Union[str, Any] = data_args.image_column_name elif "image" in column_names: a__ : Union[str, Any] = '''image''' elif "img" in column_names: a__ : str = '''img''' else: a__ : Any = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py a__ : Tuple = Compose( [ Lambda(lambda lowerCAmelCase__ : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator a__ : Union[str, Any] = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(lowerCAmelCase__ : Optional[Any] ): a__ : int = [transforms(lowerCAmelCase__ ) for image in examples[image_column_name]] a__ : List[Any] = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: a__ : Tuple = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(lowerCAmelCase__ ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: a__ : List[str] = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(lowerCAmelCase__ ) # Initialize our trainer a__ : int = Trainer( model=lowerCAmelCase__ , args=lowerCAmelCase__ , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=lowerCAmelCase__ , data_collator=lowerCAmelCase__ , ) # Training if training_args.do_train: a__ : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: a__ : Any = training_args.resume_from_checkpoint elif last_checkpoint is not None: a__ : List[Any] = last_checkpoint a__ : Tuple = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) 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: a__ : Any = trainer.evaluate() trainer.log_metrics('''eval''' , lowerCAmelCase__ ) trainer.save_metrics('''eval''' , lowerCAmelCase__ ) # Write model card and (optionally) push to hub a__ : List[Any] = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''masked-image-modeling''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-image-modeling'''], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase__ ) else: trainer.create_model_card(**lowerCAmelCase__ ) if __name__ == "__main__": main()
688
'''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 __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = 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] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[str] = randn_tensor(A__ , generator=A__ , device=A__ , dtype=A__ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) a__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(A__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __SCREAMING_SNAKE_CASE = '__DUMMY_TRANSFORMERS_USER__' __SCREAMING_SNAKE_CASE = 'Dummy User' __SCREAMING_SNAKE_CASE = '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' __SCREAMING_SNAKE_CASE = 'https://hub-ci.huggingface.co' __SCREAMING_SNAKE_CASE = CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}' __SCREAMING_SNAKE_CASE = CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}' __SCREAMING_SNAKE_CASE = Path('~/.huggingface/hub_ci_token').expanduser() @pytest.fixture def __a ( lowerCAmelCase__ : str ): monkeypatch.setattr( '''huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE''' , lowerCAmelCase__ ) @pytest.fixture def __a ( lowerCAmelCase__ : Optional[int] ): monkeypatch.setattr('''datasets.config.HF_ENDPOINT''' , lowerCAmelCase__ ) monkeypatch.setattr('''datasets.config.HUB_DATASETS_URL''' , lowerCAmelCase__ ) @pytest.fixture def __a ( lowerCAmelCase__ : Tuple ): monkeypatch.setattr('''huggingface_hub.hf_api.HfFolder.path_token''' , lowerCAmelCase__ ) @pytest.fixture def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Dict ): HfFolder.save_token(lowerCAmelCase__ ) yield HfFolder.delete_token() @pytest.fixture(scope='''session''' ) def __a ( ): return HfApi(endpoint=lowerCAmelCase__ ) @pytest.fixture(scope='''session''' ) def __a ( lowerCAmelCase__ : HfApi ): a__ : Optional[int] = HfFolder.get_token() HfFolder.save_token(lowerCAmelCase__ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(lowerCAmelCase__ ) @pytest.fixture def __a ( lowerCAmelCase__ : Any ): def _cleanup_repo(lowerCAmelCase__ : List[Any] ): hf_api.delete_repo(lowerCAmelCase__ , token=lowerCAmelCase__ , repo_type='''dataset''' ) return _cleanup_repo @pytest.fixture def __a ( lowerCAmelCase__ : Tuple ): @contextmanager def _temporary_repo(lowerCAmelCase__ : Optional[Any] ): try: yield repo_id finally: cleanup_repo(lowerCAmelCase__ ) return _temporary_repo @pytest.fixture(scope='''session''' ) def __a ( lowerCAmelCase__ : HfApi , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict ): a__ : str = F'repo_txt_data-{int(time.time() * 10E3 )}' a__ : Dict = F'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(lowerCAmelCase__ , token=lowerCAmelCase__ , repo_type='''dataset''' , private=lowerCAmelCase__ ) hf_api.upload_file( token=lowerCAmelCase__ , path_or_fileobj=str(lowerCAmelCase__ ) , path_in_repo='''data/text_data.txt''' , repo_id=lowerCAmelCase__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(lowerCAmelCase__ , token=lowerCAmelCase__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Any ): return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='''session''' ) def __a ( lowerCAmelCase__ : HfApi , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str ): a__ : str = F'repo_zipped_txt_data-{int(time.time() * 10E3 )}' a__ : Dict = F'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(lowerCAmelCase__ , token=lowerCAmelCase__ , repo_type='''dataset''' , private=lowerCAmelCase__ ) hf_api.upload_file( token=lowerCAmelCase__ , path_or_fileobj=str(lowerCAmelCase__ ) , path_in_repo='''data.zip''' , repo_id=lowerCAmelCase__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(lowerCAmelCase__ , token=lowerCAmelCase__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __a ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Any ): return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='''session''' ) def __a ( lowerCAmelCase__ : HfApi , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int] ): a__ : str = F'repo_zipped_img_data-{int(time.time() * 10E3 )}' a__ : Optional[int] = F'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(lowerCAmelCase__ , token=lowerCAmelCase__ , repo_type='''dataset''' , private=lowerCAmelCase__ ) hf_api.upload_file( token=lowerCAmelCase__ , path_or_fileobj=str(lowerCAmelCase__ ) , path_in_repo='''data.zip''' , repo_id=lowerCAmelCase__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(lowerCAmelCase__ , token=lowerCAmelCase__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any , lowerCAmelCase__ : int ): return hf_private_dataset_repo_zipped_img_data_
688
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
1
'''simple docstring''' import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class lowerCAmelCase__ ( ctypes.Structure ): """simple docstring""" __UpperCamelCase = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def __a ( ): if os.name == "nt": a__ : List[Any] = CursorInfo() a__ : int = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCAmelCase__ , ctypes.byref(lowerCAmelCase__ ) ) a__ : Optional[int] = False ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCAmelCase__ , ctypes.byref(lowerCAmelCase__ ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def __a ( ): if os.name == "nt": a__ : List[str] = CursorInfo() a__ : List[Any] = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCAmelCase__ , ctypes.byref(lowerCAmelCase__ ) ) a__ : List[str] = True ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCAmelCase__ , ctypes.byref(lowerCAmelCase__ ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def __a ( ): try: hide_cursor() yield finally: show_cursor()
688
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
1
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False" ) ) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env" ) @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 650, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "pytorch", "script": "run_ddp.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 600, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "tensorflow", "script": "run_tf_dist.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 600, "eval_accuracy": 0.6, "eval_loss": 0.7}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : List[str] ) -> List[Any]: '''simple docstring''' if self.framework == "pytorch": subprocess.run( F'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding='''utf-8''' , check=A__ , ) assert hasattr(self , '''env''' ) def __lowerCAmelCase ( self : Optional[Any] , A__ : int ) -> Dict: '''simple docstring''' a__ : int = F'{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}' # distributed data settings a__ : str = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=A__ , instance_count=A__ , instance_type=self.instance_type , debugger_hook_config=A__ , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=A__ , py_version='''py36''' , ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : List[Any] ) -> List[Any]: '''simple docstring''' TrainingJobAnalytics(A__ ).export_csv(F'{self.env.test_path}/{job_name}_metrics.csv' ) @parameterized.expand([(2,)] ) def __lowerCAmelCase ( self : Dict , A__ : Dict ) -> Dict: '''simple docstring''' a__ : Optional[Any] = self.create_estimator(A__ ) # run training estimator.fit() # result dataframe a__ : List[Any] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis a__ : str = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) a__ : Union[str, Any] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping a__ : List[str] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F'{estimator.latest_training_job.name}.json' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , A__ )
688
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spm_char.model'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'microsoft/speecht5_asr': 'https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model', 'microsoft/speecht5_tts': 'https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model', 'microsoft/speecht5_vc': 'https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model', } } __SCREAMING_SNAKE_CASE = { 'microsoft/speecht5_asr': 1_0_2_4, 'microsoft/speecht5_tts': 1_0_2_4, 'microsoft/speecht5_vc': 1_0_2_4, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : Optional[int] , A__ : Optional[int] , A__ : int="<s>" , A__ : Any="</s>" , A__ : Optional[Any]="<unk>" , A__ : Union[str, Any]="<pad>" , A__ : Optional[Dict[str, Any]] = None , **A__ : Dict , ) -> None: '''simple docstring''' a__ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A__ , eos_token=A__ , unk_token=A__ , pad_token=A__ , sp_model_kwargs=self.sp_model_kwargs , **A__ , ) a__ : List[str] = vocab_file a__ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A__ ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' return self.sp_model.get_piece_size() def __lowerCAmelCase ( self : Dict ) -> List[Any]: '''simple docstring''' a__ : List[str] = {self.convert_ids_to_tokens(A__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[str] ) -> int: '''simple docstring''' a__ : Optional[Any] = self.__dict__.copy() a__ : List[str] = None return state def __setstate__( self : Any , A__ : Optional[int] ) -> Any: '''simple docstring''' a__ : Union[str, Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a__ : Optional[Any] = {} a__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Tuple , A__ : str ) -> List[str]: '''simple docstring''' return self.sp_model.encode(A__ , out_type=A__ ) def __lowerCAmelCase ( self : Dict , A__ : Tuple ) -> Optional[Any]: '''simple docstring''' return self.sp_model.piece_to_id(A__ ) def __lowerCAmelCase ( self : Optional[int] , A__ : Dict ) -> int: '''simple docstring''' a__ : str = self.sp_model.IdToPiece(A__ ) return token def __lowerCAmelCase ( self : List[str] , A__ : List[Any] ) -> str: '''simple docstring''' a__ : Optional[Any] = [] a__ : Optional[Any] = '''''' 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 a__ : str = [] else: current_sub_tokens.append(A__ ) out_string += self.sp_model.decode(A__ ) return out_string.strip() def __lowerCAmelCase ( self : List[str] , A__ : List[Any] , A__ : Any=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 : Optional[int] , A__ : List[int] , A__ : Optional[List[int]] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A__ , token_ids_a=A__ , already_has_special_tokens=A__ ) a__ : List[str] = [1] if token_ids_a is None: return ([0] * len(A__ )) + suffix_ones return ([0] * len(A__ )) + ([0] * len(A__ )) + suffix_ones def __lowerCAmelCase ( self : str , 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 a__ : List[Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A__ ) elif not os.path.isfile(self.vocab_file ): with open(A__ , '''wb''' ) as fi: a__ : Any = self.sp_model.serialized_model_proto() fi.write(A__ ) return (out_vocab_file,)
688
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
1
'''simple docstring''' from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "ClapFeatureExtractor" __UpperCamelCase = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self : str , A__ : List[Any] , A__ : Any ) -> List[Any]: '''simple docstring''' super().__init__(A__ , A__ ) def __call__( self : int , A__ : int=None , A__ : int=None , A__ : Optional[Any]=None , **A__ : Union[str, Any] ) -> List[str]: '''simple docstring''' a__ : Any = kwargs.pop('''sampling_rate''' , A__ ) if text is None and audios is None: raise ValueError('''You have to specify either text or audios. Both cannot be none.''' ) if text is not None: a__ : Optional[int] = self.tokenizer(A__ , return_tensors=A__ , **A__ ) if audios is not None: a__ : Optional[Any] = self.feature_extractor( A__ , sampling_rate=A__ , return_tensors=A__ , **A__ ) if text is not None and audios is not None: a__ : List[Any] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**A__ ) , tensor_type=A__ ) def __lowerCAmelCase ( self : int , *A__ : List[str] , **A__ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return self.tokenizer.batch_decode(*A__ , **A__ ) def __lowerCAmelCase ( self : int , *A__ : int , **A__ : Optional[int] ) -> int: '''simple docstring''' return self.tokenizer.decode(*A__ , **A__ ) @property def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' a__ : str = self.tokenizer.model_input_names a__ : List[Any] = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
688
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __SCREAMING_SNAKE_CASE = { 'configuration_falcon': ['FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FalconConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'FALCON_PRETRAINED_MODEL_ARCHIVE_LIST', 'FalconForCausalLM', 'FalconModel', 'FalconPreTrainedModel', 'FalconForSequenceClassification', 'FalconForTokenClassification', 'FalconForQuestionAnswering', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE = { 'configuration_bert': ['BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BertConfig', 'BertOnnxConfig'], 'tokenization_bert': ['BasicTokenizer', 'BertTokenizer', 'WordpieceTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['BertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BertForMaskedLM', 'BertForMultipleChoice', 'BertForNextSentencePrediction', 'BertForPreTraining', 'BertForQuestionAnswering', 'BertForSequenceClassification', 'BertForTokenClassification', 'BertLayer', 'BertLMHeadModel', 'BertModel', 'BertPreTrainedModel', 'load_tf_weights_in_bert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFBertEmbeddings', 'TFBertForMaskedLM', 'TFBertForMultipleChoice', 'TFBertForNextSentencePrediction', 'TFBertForPreTraining', 'TFBertForQuestionAnswering', 'TFBertForSequenceClassification', 'TFBertForTokenClassification', 'TFBertLMHeadModel', 'TFBertMainLayer', 'TFBertModel', 'TFBertPreTrainedModel', ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['TFBertTokenizer'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'FlaxBertForCausalLM', 'FlaxBertForMaskedLM', 'FlaxBertForMultipleChoice', 'FlaxBertForNextSentencePrediction', 'FlaxBertForPreTraining', 'FlaxBertForQuestionAnswering', 'FlaxBertForSequenceClassification', 'FlaxBertForTokenClassification', 'FlaxBertModel', 'FlaxBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : 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 : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
1
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version __SCREAMING_SNAKE_CASE = { '<': operator.lt, '<=': operator.le, '==': operator.eq, '!=': operator.ne, '>=': operator.ge, '>': operator.gt, } def __a ( lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict ): if got_ver is None or want_ver is None: raise ValueError( F'Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider' F' reinstalling {pkg}.' ) if not ops[op](version.parse(lowerCAmelCase__ ) , version.parse(lowerCAmelCase__ ) ): raise ImportError( F'{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}' ) def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[str] = None ): a__ : int = F'\n{hint}' if hint is not None else '''''' # non-versioned check if re.match(r'''^[\w_\-\d]+$''' , lowerCAmelCase__ ): a__ , a__ , a__ : Union[str, Any] = requirement, None, None else: a__ : Union[str, Any] = re.findall(r'''^([^!=<>\s]+)([\s!=<>]{1,2}.+)''' , lowerCAmelCase__ ) if not match: raise ValueError( '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but''' F' got {requirement}' ) a__ , a__ : List[str] = match[0] a__ : Optional[Any] = want_full.split(''',''' ) # there could be multiple requirements a__ : Optional[int] = {} for w in want_range: a__ : Tuple = re.findall(r'''^([\s!=<>]{1,2})(.+)''' , lowerCAmelCase__ ) if not match: raise ValueError( '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,''' F' but got {requirement}' ) a__ , a__ : List[str] = match[0] a__ : List[Any] = want_ver if op not in ops: raise ValueError(F'{requirement}: need one of {list(ops.keys() )}, but got {op}' ) # special case if pkg == "python": a__ : Optional[Any] = '''.'''.join([str(lowerCAmelCase__ ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return # check if any version is installed try: a__ : Optional[int] = importlib.metadata.version(lowerCAmelCase__ ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'The \'{requirement}\' distribution was not found and is required by this application. {hint}' ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def __a ( lowerCAmelCase__ : Any ): a__ : Union[str, Any] = '''Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main''' return require_version(lowerCAmelCase__ , lowerCAmelCase__ )
688
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
1
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : 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 : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __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 a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
1
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : int = 4000000 ): a__ : Union[str, Any] = [] a__ , a__ : Optional[int] = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(lowerCAmelCase__ ) a__ , a__ : str = b, a + b return sum(lowerCAmelCase__ ) if __name__ == "__main__": print(f'{solution() = }')
688
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
1
'''simple docstring''' from argparse import ArgumentParser from .env import EnvironmentCommand def __a ( ): a__ : Optional[int] = ArgumentParser('''Diffusers CLI tool''' , usage='''diffusers-cli <command> [<args>]''' ) a__ : List[Any] = parser.add_subparsers(help='''diffusers-cli command helpers''' ) # Register commands EnvironmentCommand.register_subcommand(lowerCAmelCase__ ) # Let's go a__ : Union[str, Any] = parser.parse_args() if not hasattr(lowerCAmelCase__ , '''func''' ): parser.print_help() exit(1 ) # Run a__ : Any = args.func(lowerCAmelCase__ ) service.run() if __name__ == "__main__": main()
688
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
1
'''simple docstring''' import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'artists_file': 'artists.json', 'lyrics_file': 'lyrics.json', 'genres_file': 'genres.json', } __SCREAMING_SNAKE_CASE = { 'artists_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json', }, 'genres_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json', }, 'lyrics_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json', }, } __SCREAMING_SNAKE_CASE = { 'jukebox': 5_1_2, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_LYRIC_TOKENS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : Optional[int] , A__ : Any , A__ : List[Any] , A__ : Tuple , A__ : Any=["v3", "v2", "v2"] , A__ : Union[str, Any]=5_1_2 , A__ : Tuple=5 , A__ : List[str]="<|endoftext|>" , **A__ : List[Any] , ) -> Tuple: '''simple docstring''' a__ : Union[str, Any] = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else unk_token super().__init__( unk_token=A__ , n_genres=A__ , version=A__ , max_n_lyric_tokens=A__ , **A__ , ) a__ : List[str] = version a__ : Optional[Any] = max_n_lyric_tokens a__ : Tuple = n_genres with open(A__ , encoding='''utf-8''' ) as vocab_handle: a__ : List[Any] = json.load(A__ ) with open(A__ , encoding='''utf-8''' ) as vocab_handle: a__ : Any = json.load(A__ ) with open(A__ , encoding='''utf-8''' ) as vocab_handle: a__ : Dict = json.load(A__ ) a__ : Tuple = r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 7_9: a__ : str = oov.replace(r'''\-\'''' , r'''\-+\'''' ) a__ : List[str] = regex.compile(A__ ) a__ : List[str] = {v: k for k, v in self.artists_encoder.items()} a__ : Optional[Any] = {v: k for k, v in self.genres_encoder.items()} a__ : Union[str, Any] = {v: k for k, v in self.lyrics_encoder.items()} @property def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def __lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , A__ : List[str] , A__ : Dict ) -> Any: '''simple docstring''' a__ : Union[str, Any] = [self.artists_encoder.get(A__ , 0 ) for artist in list_artists] for genres in range(len(A__ ) ): a__ : Dict = [self.genres_encoder.get(A__ , 0 ) for genre in list_genres[genres]] a__ : Union[str, Any] = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) a__ : Dict = [[self.lyrics_encoder.get(A__ , 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def __lowerCAmelCase ( self : Optional[Any] , A__ : Tuple ) -> Optional[Any]: '''simple docstring''' return list(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , A__ : str , A__ : int , **A__ : str ) -> Any: '''simple docstring''' a__ , a__ , a__ : Optional[int] = self.prepare_for_tokenization(A__ , A__ , A__ ) a__ : Any = self._tokenize(A__ ) return artist, genre, lyrics def __lowerCAmelCase ( self : Dict , A__ : str , A__ : str , A__ : str , A__ : bool = False ) -> Tuple[str, str, str, Dict[str, Any]]: '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": a__ : Optional[Any] = artists[idx].lower() a__ : Union[str, Any] = [genres[idx].lower()] else: a__ : str = self._normalize(artists[idx] ) + '''.v2''' a__ : Union[str, Any] = [ self._normalize(A__ ) + '''.v2''' for genre in genres[idx].split('''_''' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": a__ : Any = regex.compile(r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' ) a__ : str = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' a__ : List[Any] = {vocab[index]: index + 1 for index in range(len(A__ ) )} a__ : int = 0 a__ : List[str] = len(A__ ) + 1 a__ : Any = self.vocab a__ : List[str] = {v: k for k, v in self.vocab.items()} a__ : Any = '''''' else: a__ : Any = regex.compile(r'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''' ) a__ : Any = self._run_strip_accents(A__ ) a__ : Dict = lyrics.replace('''\\''' , '''\n''' ) a__ : Union[str, Any] = self.out_of_vocab.sub('''''' , A__ ), [], [] return artists, genres, lyrics def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[Any] ) -> str: '''simple docstring''' a__ : Union[str, Any] = unicodedata.normalize('''NFD''' , A__ ) a__ : int = [] for char in text: a__ : Union[str, Any] = unicodedata.category(A__ ) if cat == "Mn": continue output.append(A__ ) return "".join(A__ ) def __lowerCAmelCase ( self : Optional[int] , A__ : str ) -> str: '''simple docstring''' a__ : List[Any] = ( [chr(A__ ) for i in range(ord('''a''' ) , ord('''z''' ) + 1 )] + [chr(A__ ) for i in range(ord('''A''' ) , ord('''Z''' ) + 1 )] + [chr(A__ ) for i in range(ord('''0''' ) , ord('''9''' ) + 1 )] + ['''.'''] ) a__ : Dict = frozenset(A__ ) a__ : Tuple = re.compile(r'''_+''' ) a__ : Optional[int] = ''''''.join([c if c in accepted else '''_''' for c in text.lower()] ) a__ : Any = pattern.sub('''_''' , A__ ).strip('''_''' ) return text def __lowerCAmelCase ( self : Tuple , A__ : List[str] ) -> str: '''simple docstring''' return " ".join(A__ ) def __lowerCAmelCase ( self : Optional[Any] , A__ : int , A__ : Optional[Union[str, TensorType]] = None , A__ : bool = False ) -> int: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : Optional[Any] = TensorType(A__ ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''' ) import tensorflow as tf a__ : Dict = tf.constant a__ : Optional[Any] = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''' ) import torch a__ : Optional[Any] = torch.tensor a__ : int = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''' ) import jax.numpy as jnp # noqa: F811 a__ : str = jnp.array a__ : str = _is_jax else: a__ : int = np.asarray a__ : List[str] = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: a__ : int = [inputs] if not is_tensor(A__ ): a__ : str = as_tensor(A__ ) except: # noqa E722 raise ValueError( '''Unable to create tensor, you should probably activate truncation and/or padding ''' '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''' ) return inputs def __call__( self : Any , A__ : Union[str, Any] , A__ : List[Any] , A__ : str="" , A__ : str="pt" ) -> BatchEncoding: '''simple docstring''' a__ : Dict = [0, 0, 0] a__ : str = [artist] * len(self.version ) a__ : Optional[int] = [genres] * len(self.version ) a__ , a__ , a__ : Union[str, Any] = self.tokenize(A__ , A__ , A__ ) a__ , a__ , a__ : Any = self._convert_token_to_id(A__ , A__ , A__ ) a__ : str = [-INFINITY] * len(full_tokens[-1] ) a__ : Optional[Any] = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=A__ ) for i in range(len(self.version ) ) ] return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks} ) 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 a__ : Optional[Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''artists_file'''] ) with open(A__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.artists_encoder , ensure_ascii=A__ ) ) a__ : List[Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''] ) with open(A__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.genres_encoder , ensure_ascii=A__ ) ) a__ : Optional[Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''] ) with open(A__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.lyrics_encoder , ensure_ascii=A__ ) ) return (artists_file, genres_file, lyrics_file) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[Any] , A__ : Dict ) -> Union[str, Any]: '''simple docstring''' a__ : Tuple = self.artists_decoder.get(A__ ) a__ : Any = [self.genres_decoder.get(A__ ) for genre in genres_index] a__ : Any = [self.lyrics_decoder.get(A__ ) for character in lyric_index] return artist, genres, lyrics
688
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
1
'''simple docstring''' import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = RoFormerTokenizer __UpperCamelCase = RoFormerTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : Dict ) -> Tuple: '''simple docstring''' super().setUp() def __lowerCAmelCase ( self : Dict , **A__ : List[str] ) -> Tuple: '''simple docstring''' return self.tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''' , **A__ ) def __lowerCAmelCase ( self : Optional[Any] , **A__ : List[Any] ) -> int: '''simple docstring''' return self.rust_tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''' , **A__ ) def __lowerCAmelCase ( self : Dict ) -> List[str]: '''simple docstring''' a__ : Optional[Any] = '''永和服装饰品有限公司,今天天气非常好''' a__ : Tuple = '''永和 服装 饰品 有限公司 , 今 天 天 气 非常 好''' return input_text, output_text def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' a__ : Union[str, Any] = self.get_tokenizer() a__ , a__ : List[str] = self.get_chinese_input_output_texts() a__ : Dict = tokenizer.tokenize(A__ ) self.assertListEqual(A__ , output_text.split() ) a__ : Tuple = tokens + [tokenizer.unk_token] a__ : Optional[int] = [2_2_9_4_3, 2_1_3_3_2, 3_4_4_3_1, 4_5_9_0_4, 1_1_7, 3_0_6, 1_2_3_1, 1_2_3_1, 2_6_5_3, 3_3_9_9_4, 1_2_6_6, 1_0_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' a__ : str = self.get_rust_tokenizer() a__ , a__ : Union[str, Any] = self.get_chinese_input_output_texts() a__ : Tuple = tokenizer.tokenize(A__ ) self.assertListEqual(A__ , output_text.split() ) a__ : Optional[Any] = tokens + [tokenizer.unk_token] a__ : Any = [2_2_9_4_3, 2_1_3_3_2, 3_4_4_3_1, 4_5_9_0_4, 1_1_7, 3_0_6, 1_2_3_1, 1_2_3_1, 2_6_5_3, 3_3_9_9_4, 1_2_6_6, 1_0_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ ) def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' pass def __lowerCAmelCase ( self : Tuple ) -> Dict: '''simple docstring''' pass def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' pass
688
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
1
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __SCREAMING_SNAKE_CASE = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = 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 flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
1
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __SCREAMING_SNAKE_CASE = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __SCREAMING_SNAKE_CASE = 'main' # Default branch name __SCREAMING_SNAKE_CASE = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) __SCREAMING_SNAKE_CASE = 'aaaaaaa' # This commit does not exist, so we should 404. __SCREAMING_SNAKE_CASE = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes __SCREAMING_SNAKE_CASE = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def __a ( ): print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def __a ( ): print('''Bonjour!''' ) yield print('''Au revoir!''' ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : int ) -> Union[str, Any]: '''simple docstring''' assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def __lowerCAmelCase ( self : Optional[Any] , A__ : Any ) -> Any: '''simple docstring''' with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> Tuple: '''simple docstring''' with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def __lowerCAmelCase ( self : Tuple , A__ : Dict ) -> Dict: '''simple docstring''' with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def __lowerCAmelCase ( self : Union[str, Any] ) -> str: '''simple docstring''' self.assertEqual(find_labels(A__ ) , ['''labels'''] ) self.assertEqual(find_labels(A__ ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(A__ ) , ['''start_positions''', '''end_positions'''] ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass self.assertEqual(find_labels(A__ ) , ['''labels'''] ) @require_tf def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertEqual(find_labels(A__ ) , ['''labels'''] ) self.assertEqual(find_labels(A__ ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(A__ ) , ['''start_positions''', '''end_positions'''] ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass self.assertEqual(find_labels(A__ ) , ['''labels'''] ) @require_flax def __lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' self.assertEqual(find_labels(A__ ) , [] ) self.assertEqual(find_labels(A__ ) , [] ) self.assertEqual(find_labels(A__ ) , [] ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass self.assertEqual(find_labels(A__ ) , [] )
688
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
1
'''simple docstring''' from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __lt__( self : Optional[int] , A__ : Any ) -> int: '''simple docstring''' return self[-1] < other[-1] def __eq__( self : Dict , A__ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' return self[-1] == other[-1] def __a ( lowerCAmelCase__ : list ): a__ : list[Stack] = [] # sort into stacks for element in collection: a__ : List[Any] = Stack([element] ) a__ : Optional[int] = bisect_left(lowerCAmelCase__ , lowerCAmelCase__ ) if i != len(lowerCAmelCase__ ): stacks[i].append(lowerCAmelCase__ ) else: stacks.append(lowerCAmelCase__ ) # use a heap-based merge to merge stack efficiently a__ : List[str] = merge(*(reversed(lowerCAmelCase__ ) for stack in stacks) ) return collection if __name__ == "__main__": __SCREAMING_SNAKE_CASE = input('Enter numbers separated by a comma:\n').strip() __SCREAMING_SNAKE_CASE = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
688
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
1
'''simple docstring''' import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __SCREAMING_SNAKE_CASE = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) __SCREAMING_SNAKE_CASE = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def __a ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict ): a__ : Dict = SavedModel() a__ : List[str] = [] with open(os.path.join(lowerCAmelCase__ , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: a__ : Tuple = json.load(lowerCAmelCase__ )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(lowerCAmelCase__ )] ) with open(lowerCAmelCase__ , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) a__ : List[str] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want a__ : Any = sorted(lowerCAmelCase__ ) a__ : Optional[Any] = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(lowerCAmelCase__ ) if strict and len(lowerCAmelCase__ ) > 0: raise Exception(F'Found the following incompatible ops for the opset {opset}:\n' + incompatible_ops ) elif len(lowerCAmelCase__ ) > 0: print(F'Found the following incompatible ops for the opset {opset}:' ) print(*lowerCAmelCase__ , sep='''\n''' ) else: print(F'The saved model {saved_model_path} can properly be converted with ONNX.' ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=1_2, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) __SCREAMING_SNAKE_CASE = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
688
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
1
'''simple docstring''' import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : str = "▁" , A__ : bool = True , A__ : Union[str, AddedToken] = "<unk>" , A__ : Union[str, AddedToken] = "</s>" , A__ : Union[str, AddedToken] = "<pad>" , ) -> int: '''simple docstring''' a__ : List[Any] = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } a__ : Tuple = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): a__ : List[Any] = token_dict['''token'''] a__ : Optional[int] = Tokenizer(Unigram() ) a__ : List[str] = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''' ) , ''' ''' ), normalizers.Lowercase(), ] ) a__ : List[Any] = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=A__ , add_prefix_space=A__ ), pre_tokenizers.Digits(individual_digits=A__ ), pre_tokenizers.Punctuation(), ] ) a__ : Any = decoders.Metaspace(replacement=A__ , add_prefix_space=A__ ) a__ : List[Any] = TemplateProcessing( single=F'$A {self.special_tokens["eos"]["token"]}' , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) a__ : str = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(A__ , A__ ) def __lowerCAmelCase ( self : Dict , A__ : Union[str, List[str]] , A__ : int = 8_0_0_0 , A__ : bool = True , ) -> Optional[Any]: '''simple docstring''' a__ : Tuple = trainers.UnigramTrainer( vocab_size=A__ , special_tokens=self.special_tokens_list , show_progress=A__ , ) if isinstance(A__ , A__ ): a__ : Optional[Any] = [files] self._tokenizer.train(A__ , trainer=A__ ) self.add_unk_id() def __lowerCAmelCase ( self : Optional[Any] , A__ : Union[Iterator[str], Iterator[Iterator[str]]] , A__ : int = 8_0_0_0 , A__ : bool = True , ) -> Optional[int]: '''simple docstring''' a__ : str = trainers.UnigramTrainer( vocab_size=A__ , special_tokens=self.special_tokens_list , show_progress=A__ , ) self._tokenizer.train_from_iterator(A__ , trainer=A__ ) self.add_unk_id() def __lowerCAmelCase ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = json.loads(self._tokenizer.to_str() ) a__ : List[Any] = self.special_tokens['''unk''']['''id'''] a__ : List[Any] = Tokenizer.from_str(json.dumps(A__ ) )
688
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
1
'''simple docstring''' import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = OpenAIGPTTokenizer __UpperCamelCase = OpenAIGPTTokenizerFast __UpperCamelCase = True __UpperCamelCase = False def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt a__ : List[str] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] a__ : int = dict(zip(A__ , range(len(A__ ) ) ) ) a__ : Dict = ['''#version: 0.2''', '''l o''', '''lo w''', '''e r</w>''', ''''''] a__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) a__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(A__ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(A__ ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple ) -> int: '''simple docstring''' return "lower newer", "lower newer" def __lowerCAmelCase ( self : List[str] ) -> List[Any]: '''simple docstring''' a__ : Tuple = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) a__ : Tuple = '''lower''' a__ : int = ['''low''', '''er</w>'''] a__ : Optional[Any] = tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Dict = tokens + ['''<unk>'''] a__ : str = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ ) def __lowerCAmelCase ( self : Tuple , A__ : int=1_5 ) -> Optional[int]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): a__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) # Simple input a__ : List[str] = '''This is a simple input''' a__ : int = ['''This is a simple input 1''', '''This is a simple input 2'''] a__ : List[str] = ('''This is a simple input''', '''This is a pair''') a__ : Optional[int] = [ ('''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 __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' pass @require_ftfy @require_spacy @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass
688
'''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 __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = 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] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[str] = randn_tensor(A__ , generator=A__ , device=A__ , dtype=A__ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) a__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(A__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[str] = randn_tensor(A__ , generator=A__ , device=A__ , dtype=A__ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) a__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(A__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __SCREAMING_SNAKE_CASE = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ..utils import _LazyModule __SCREAMING_SNAKE_CASE = { 'config': [ 'EXTERNAL_DATA_FORMAT_SIZE_LIMIT', 'OnnxConfig', 'OnnxConfigWithPast', 'OnnxSeq2SeqConfigWithPast', 'PatchingSpec', ], 'convert': ['export', 'validate_model_outputs'], 'features': ['FeaturesManager'], 'utils': ['ParameterFormat', 'compute_serialized_parameters_size'], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) def __lowercase ( snake_case, snake_case=False, snake_case=False ): """simple docstring""" __magic_name__ :Any = '''backbone.''' if is_semantic else '''''' __magic_name__ :Tuple = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''{prefix}blocks.{i}.norm1.weight''', f'''beit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.norm1.bias''', f'''beit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''{prefix}blocks.{i}.attn.proj.weight''', f'''beit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''{prefix}blocks.{i}.attn.proj.bias''', f'''beit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''{prefix}blocks.{i}.norm2.weight''', f'''beit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.norm2.bias''', f'''beit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc1.weight''', f'''beit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc1.bias''', f'''beit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc2.weight''', f'''beit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc2.bias''', f'''beit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ (f'''{prefix}cls_token''', '''beit.embeddings.cls_token'''), (f'''{prefix}patch_embed.proj.weight''', '''beit.embeddings.patch_embeddings.projection.weight'''), (f'''{prefix}patch_embed.proj.bias''', '''beit.embeddings.patch_embeddings.projection.bias'''), (f'''{prefix}pos_embed''', '''beit.embeddings.position_embeddings'''), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ('''mask_token''', '''beit.embeddings.mask_token'''), ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ] ) else: # layernorm + classification head rename_keys.extend( [ ('''fc_norm.weight''', '''beit.pooler.layernorm.weight'''), ('''fc_norm.bias''', '''beit.pooler.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def __lowercase ( snake_case, snake_case, snake_case=False, snake_case=False ): """simple docstring""" for i in range(config.num_hidden_layers ): __magic_name__ :str = '''backbone.''' if is_semantic else '''''' # queries, keys and values __magic_name__ :Union[str, Any] = state_dict.pop(f'''{prefix}blocks.{i}.attn.qkv.weight''' ) __magic_name__ :str = state_dict.pop(f'''{prefix}blocks.{i}.attn.q_bias''' ) __magic_name__ :Optional[Any] = state_dict.pop(f'''{prefix}blocks.{i}.attn.v_bias''' ) __magic_name__ :Optional[Any] = in_proj_weight[ : config.hidden_size, : ] __magic_name__ :str = q_bias __magic_name__ :int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __magic_name__ :Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] __magic_name__ :Tuple = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained __magic_name__ :Optional[Any] = state_dict.pop(f'''{prefix}blocks.{i}.gamma_1''' ) __magic_name__ :Optional[Any] = state_dict.pop(f'''{prefix}blocks.{i}.gamma_2''' ) __magic_name__ :List[Any] = gamma_a __magic_name__ :Optional[int] = gamma_a def __lowercase ( snake_case, snake_case, snake_case ): """simple docstring""" __magic_name__ :Union[str, Any] = dct.pop(snake_case ) __magic_name__ :Tuple = val def __lowercase ( ): """simple docstring""" __magic_name__ :str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __magic_name__ :List[Any] = Image.open(requests.get(snake_case, stream=snake_case ).raw ) return im @torch.no_grad() def __lowercase ( snake_case, snake_case, snake_case=False ): """simple docstring""" __magic_name__ :Tuple = False if '''rvlcdip''' in checkpoint_url else True __magic_name__ :int = BeitConfig(use_absolute_position_embeddings=snake_case, use_mask_token=snake_case ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: __magic_name__ :Tuple = 1_0_2_4 __magic_name__ :int = 4_0_9_6 __magic_name__ :List[Any] = 2_4 __magic_name__ :Union[str, Any] = 1_6 # labels if "rvlcdip" in checkpoint_url: __magic_name__ :List[str] = 1_6 __magic_name__ :Dict = '''huggingface/label-files''' __magic_name__ :int = '''rvlcdip-id2label.json''' __magic_name__ :Optional[int] = json.load(open(hf_hub_download(snake_case, snake_case, repo_type='''dataset''' ), '''r''' ) ) __magic_name__ :List[str] = {int(snake_case ): v for k, v in idalabel.items()} __magic_name__ :List[str] = idalabel __magic_name__ :Tuple = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys __magic_name__ :Union[str, Any] = torch.hub.load_state_dict_from_url(snake_case, map_location='''cpu''' )['''model'''] __magic_name__ :Dict = create_rename_keys(snake_case, has_lm_head=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, has_lm_head=snake_case ) # load HuggingFace model __magic_name__ :Union[str, Any] = BeitForMaskedImageModeling(snake_case ) if has_lm_head else BeitForImageClassification(snake_case ) model.eval() model.load_state_dict(snake_case ) # Check outputs on an image __magic_name__ :Dict = BeitImageProcessor( size=config.image_size, resample=PILImageResampling.BILINEAR, do_center_crop=snake_case ) __magic_name__ :int = prepare_img() __magic_name__ :Dict = image_processor(images=snake_case, return_tensors='''pt''' ) __magic_name__ :str = encoding['''pixel_values'''] __magic_name__ :List[str] = model(snake_case ) __magic_name__ :int = outputs.logits # verify logits __magic_name__ :Optional[int] = [1, 1_6] if '''rvlcdip''' in checkpoint_url else [1, 1_9_6, 8_1_9_2] assert logits.shape == torch.Size(snake_case ), "Shape 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 image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(snake_case ) if push_to_hub: if has_lm_head: __magic_name__ :Union[str, Any] = '''dit-base''' if '''base''' in checkpoint_url else '''dit-large''' else: __magic_name__ :str = '''dit-base-finetuned-rvlcdip''' if '''dit-b''' in checkpoint_url else '''dit-large-finetuned-rvlcdip''' image_processor.push_to_hub( repo_path_or_name=Path(snake_case, snake_case ), organization='''nielsr''', commit_message='''Add image processor''', use_temp_dir=snake_case, ) model.push_to_hub( repo_path_or_name=Path(snake_case, snake_case ), organization='''nielsr''', commit_message='''Add model''', use_temp_dir=snake_case, ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser() parser.add_argument( """--checkpoint_url""", default="""https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth""", type=str, help="""URL to the original PyTorch checkpoint (.pth file).""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
0
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
0
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __snake_case = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class __lowerCamelCase (unittest.TestCase ): _lowercase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowercase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _lowercase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _lowercase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def snake_case_ ( self: Tuple,A_: List[str],A_: str,A_: str ): '''simple docstring''' __UpperCamelCase = ZeroShotClassificationPipeline( model=A_,tokenizer=A_,candidate_labels=['polics', 'health'] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def snake_case_ ( self: Optional[Any],A_: Tuple,A_: List[Any] ): '''simple docstring''' __UpperCamelCase = classifier('Who are you voting for in 2020?',candidate_labels='politics' ) self.assertEqual(A_,{'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) # No kwarg __UpperCamelCase = classifier('Who are you voting for in 2020?',['politics'] ) self.assertEqual(A_,{'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) __UpperCamelCase = classifier('Who are you voting for in 2020?',candidate_labels=['politics'] ) self.assertEqual(A_,{'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) __UpperCamelCase = classifier('Who are you voting for in 2020?',candidate_labels='politics, public health' ) self.assertEqual( A_,{'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ),1.0 ) __UpperCamelCase = classifier('Who are you voting for in 2020?',candidate_labels=['politics', 'public health'] ) self.assertEqual( A_,{'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ),1.0 ) __UpperCamelCase = classifier( 'Who are you voting for in 2020?',candidate_labels='politics',hypothesis_template='This text is about {}' ) self.assertEqual(A_,{'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) # https://github.com/huggingface/transformers/issues/13846 __UpperCamelCase = classifier(['I am happy'],['positive', 'negative'] ) self.assertEqual( A_,[ {'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} for i in range(1 ) ],) __UpperCamelCase = classifier(['I am happy', 'I am sad'],['positive', 'negative'] ) self.assertEqual( A_,[ {'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} for i in range(2 ) ],) with self.assertRaises(A_ ): classifier('',candidate_labels='politics' ) with self.assertRaises(A_ ): classifier(A_,candidate_labels='politics' ) with self.assertRaises(A_ ): classifier('Who are you voting for in 2020?',candidate_labels='' ) with self.assertRaises(A_ ): classifier('Who are you voting for in 2020?',candidate_labels=A_ ) with self.assertRaises(A_ ): classifier( 'Who are you voting for in 2020?',candidate_labels='politics',hypothesis_template='Not formatting template',) with self.assertRaises(A_ ): classifier( 'Who are you voting for in 2020?',candidate_labels='politics',hypothesis_template=A_,) self.run_entailment_id(A_ ) def snake_case_ ( self: List[str],A_: Pipeline ): '''simple docstring''' __UpperCamelCase = zero_shot_classifier.model.config __UpperCamelCase = config.labelaid __UpperCamelCase = zero_shot_classifier.entailment_id __UpperCamelCase = {'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2} self.assertEqual(zero_shot_classifier.entailment_id,-1 ) __UpperCamelCase = {'entailment': 0, 'neutral': 1, 'contradiction': 2} self.assertEqual(zero_shot_classifier.entailment_id,0 ) __UpperCamelCase = {'ENTAIL': 0, 'NON-ENTAIL': 1} self.assertEqual(zero_shot_classifier.entailment_id,0 ) __UpperCamelCase = {'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0} self.assertEqual(zero_shot_classifier.entailment_id,2 ) __UpperCamelCase = original_labelaid self.assertEqual(A_,zero_shot_classifier.entailment_id ) @require_torch def snake_case_ ( self: List[Any] ): '''simple docstring''' __UpperCamelCase = pipeline( 'zero-shot-classification',model='sshleifer/tiny-distilbert-base-cased-distilled-squad',framework='pt',) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( 'Who are you voting for in 2020?' * 100,candidate_labels=['politics', 'public health', 'science'] ) @require_torch def snake_case_ ( self: str ): '''simple docstring''' __UpperCamelCase = pipeline( 'zero-shot-classification',model='sshleifer/tiny-distilbert-base-cased-distilled-squad',framework='pt',) __UpperCamelCase = zero_shot_classifier( 'Who are you voting for in 2020?',candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ),{ 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], },) @require_tf def snake_case_ ( self: List[str] ): '''simple docstring''' __UpperCamelCase = pipeline( 'zero-shot-classification',model='sshleifer/tiny-distilbert-base-cased-distilled-squad',framework='tf',) __UpperCamelCase = zero_shot_classifier( 'Who are you voting for in 2020?',candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ),{ 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], },) @slow @require_torch def snake_case_ ( self: Tuple ): '''simple docstring''' __UpperCamelCase = pipeline('zero-shot-classification',model='roberta-large-mnli',framework='pt' ) __UpperCamelCase = zero_shot_classifier( 'Who are you voting for in 2020?',candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ),{ 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], },) __UpperCamelCase = zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.',candidate_labels=['machine learning', 'statistics', 'translation', 'vision'],multi_label=A_,) self.assertEqual( nested_simplify(A_ ),{ 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], },) @slow @require_tf def snake_case_ ( self: Tuple ): '''simple docstring''' __UpperCamelCase = pipeline('zero-shot-classification',model='roberta-large-mnli',framework='tf' ) __UpperCamelCase = zero_shot_classifier( 'Who are you voting for in 2020?',candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ),{ 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], },) __UpperCamelCase = zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.',candidate_labels=['machine learning', 'statistics', 'translation', 'vision'],multi_label=A_,) self.assertEqual( nested_simplify(A_ ),{ 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], },)
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
0
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 UpperCAmelCase_ = datasets.utils.logging.get_logger(__name__) @dataclass class lowerCamelCase__ ( datasets.BuilderConfig): """simple docstring""" a__ : Optional[datasets.Features] = None a__ : str = "utf-8" a__ : Optional[str] = None a__ : Optional[str] = None a__ : bool = True # deprecated a__ : Optional[int] = None # deprecated a__ : int = 10 << 20 # 10MB a__ : Optional[bool] = None class lowerCamelCase__ ( datasets.ArrowBasedBuilder): """simple docstring""" a__ : List[Any] = JsonConfig def snake_case_ ( self : Any ) -> List[str]: if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' ) _A = 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 : int , __lowerCAmelCase : Dict ) -> Any: if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) _A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__lowerCAmelCase , (str, list, tuple) ): _A = data_files if isinstance(__lowerCAmelCase , __lowerCAmelCase ): _A = [files] _A = [dl_manager.iter_files(__lowerCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] _A = [] for split_name, files in data_files.items(): if isinstance(__lowerCAmelCase , __lowerCAmelCase ): _A = [files] _A = [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 : Dict , __lowerCAmelCase : pa.Table ) -> pa.Table: if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): _A = self.config.features.arrow_schema.field(__lowerCAmelCase ).type _A = 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 _A = table_cast(__lowerCAmelCase , self.config.features.arrow_schema ) return pa_table def snake_case_ ( self : Any , __lowerCAmelCase : str ) -> int: 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: _A = json.load(__lowerCAmelCase ) # We keep only the field we are interested in _A = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__lowerCAmelCase , (list, tuple) ): _A = set().union(*[row.keys() for row in dataset] ) _A = {col: [row.get(__lowerCAmelCase ) for row in dataset] for col in keys} else: _A = dataset _A = 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: _A = 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 _A = max(self.config.chunksize // 32 , 16 << 10 ) _A = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: _A = 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": _A = batch.decode(self.config.encoding , errors=__lowerCAmelCase ).encode('''utf-8''' ) try: while True: try: _A = 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: _A = 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: _A = set().union(*[row.keys() for row in dataset] ) _A = {col: [row.get(__lowerCAmelCase ) for row in dataset] for col in keys} _A = 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
2
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
0
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase): def __init__( self , A_ , A_=3 , A_=32 , A_=3 , A_=10 , A_=[10, 20, 30, 40] , A_=[1, 1, 2, 1] , A_=True , A_=True , A_="relu" , A_=3 , A_=None , )-> int: '''simple docstring''' UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = num_channels UpperCamelCase = embeddings_size UpperCamelCase = hidden_sizes UpperCamelCase = depths UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = hidden_act UpperCamelCase = num_labels UpperCamelCase = scope UpperCamelCase = len(A_ ) def UpperCAmelCase_ ( self )-> Optional[Any]: '''simple docstring''' UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = self.get_config() return config, pixel_values def UpperCAmelCase_ ( self )-> Optional[int]: '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def UpperCAmelCase_ ( self , A_ , A_ )-> Union[str, Any]: '''simple docstring''' UpperCamelCase = FlaxRegNetModel(config=A_ ) UpperCamelCase = model(A_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCAmelCase_ ( self , A_ , A_ )-> Tuple: '''simple docstring''' UpperCamelCase = self.num_labels UpperCamelCase = FlaxRegNetForImageClassification(config=A_ ) UpperCamelCase = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self )-> List[Any]: '''simple docstring''' UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class SCREAMING_SNAKE_CASE__ ( snake_case_ , unittest.TestCase): lowerCAmelCase_ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def UpperCAmelCase_ ( self )-> None: '''simple docstring''' UpperCamelCase = FlaxRegNetModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=A_ , has_text_modality=A_ ) def UpperCAmelCase_ ( self )-> int: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase_ ( self )-> Optional[Any]: '''simple docstring''' return def UpperCAmelCase_ ( self )-> Any: '''simple docstring''' UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def UpperCAmelCase_ ( self )-> Tuple: '''simple docstring''' UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) @unittest.skip(reason='RegNet does not use inputs_embeds' ) def UpperCAmelCase_ ( self )-> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason='RegNet does not support input and output embeddings' ) def UpperCAmelCase_ ( self )-> Optional[int]: '''simple docstring''' pass def UpperCAmelCase_ ( self )-> Dict: '''simple docstring''' UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(A_ ) UpperCamelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , A_ ) def UpperCAmelCase_ ( self )-> int: '''simple docstring''' def check_hidden_states_output(A_ , A_ , A_ ): UpperCamelCase = model_class(A_ ) UpperCamelCase = model(**self._prepare_for_class(A_ , A_ ) ) UpperCamelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase = self.model_tester.num_stages self.assertEqual(len(A_ ) , expected_num_stages + 1 ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(A_ , A_ , A_ ) def UpperCAmelCase_ ( self )-> Optional[Any]: '''simple docstring''' UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase = self._prepare_for_class(A_ , A_ ) UpperCamelCase = model_class(A_ ) @jax.jit def model_jitted(A_ , **A_ ): return model(pixel_values=A_ , **A_ ) with self.subTest('JIT Enabled' ): UpperCamelCase = model_jitted(**A_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCamelCase = 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 A_( ): UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase): @cached_property def UpperCAmelCase_ ( self )-> Optional[Any]: '''simple docstring''' return AutoImageProcessor.from_pretrained('facebook/regnet-y-040' ) if is_vision_available() else None @slow def UpperCAmelCase_ ( self )-> List[Any]: '''simple docstring''' UpperCamelCase = FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040' ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=A_ , return_tensors='np' ) UpperCamelCase = model(**A_ ) # verify the logits UpperCamelCase = (1, 1000) self.assertEqual(outputs.logits.shape , A_ ) UpperCamelCase = jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , A_ , atol=1e-4 ) )
3
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
0
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __UpperCamelCase : int = '''pt''' elif is_tf_available(): __UpperCamelCase : Optional[Any] = '''tf''' else: __UpperCamelCase : int = '''jax''' class a ( a__ , unittest.TestCase ): snake_case__ = ByTaTokenizer snake_case__ = False def UpperCamelCase__ ( self ): """simple docstring""" super().setUp() lowerCAmelCase = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase__ ( self ): """simple docstring""" return ByTaTokenizer.from_pretrained('google/byt5-small' ) def UpperCamelCase__ ( self , **_snake_case ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **_snake_case ) def UpperCamelCase__ ( self , _snake_case , _snake_case=False , _snake_case=20 , _snake_case=5 ): """simple docstring""" lowerCAmelCase = [] for i in range(len(_snake_case ) ): try: lowerCAmelCase = tokenizer.decode([i] , clean_up_tokenization_spaces=_snake_case ) except UnicodeDecodeError: pass toks.append((i, tok) ) lowerCAmelCase = list(filter(lambda _snake_case : re.match(r'^[ a-zA-Z]+$' , t[1] ) , _snake_case ) ) lowerCAmelCase = list(filter(lambda _snake_case : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_snake_case ) , _snake_case ) ) if max_length is not None and len(_snake_case ) > max_length: lowerCAmelCase = toks[:max_length] if min_length is not None and len(_snake_case ) < min_length and len(_snake_case ) > 0: while len(_snake_case ) < min_length: lowerCAmelCase = toks + toks # toks_str = [t[1] for t in toks] lowerCAmelCase = [t[0] for t in toks] # Ensure consistency lowerCAmelCase = tokenizer.decode(_snake_case , clean_up_tokenization_spaces=_snake_case ) if " " not in output_txt and len(_snake_case ) > 1: lowerCAmelCase = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_snake_case ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_snake_case ) ) if with_prefix_space: lowerCAmelCase = ' ' + output_txt lowerCAmelCase = tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) return output_txt, output_ids def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.ta_base_tokenizer lowerCAmelCase = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) lowerCAmelCase = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.ta_base_tokenizer lowerCAmelCase = 'Unicode €.' lowerCAmelCase = tokenizer(_snake_case ) lowerCAmelCase = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['input_ids'] , _snake_case ) # decoding lowerCAmelCase = tokenizer.decode(_snake_case ) self.assertEqual(_snake_case , 'Unicode €.</s>' ) lowerCAmelCase = tokenizer('e è é ê ë' ) lowerCAmelCase = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['input_ids'] , _snake_case ) # decoding lowerCAmelCase = tokenizer.decode(_snake_case ) self.assertEqual(_snake_case , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.ta_base_tokenizer lowerCAmelCase = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off lowerCAmelCase = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on lowerCAmelCase = tokenizer(_snake_case , padding=_snake_case , return_tensors=_snake_case ) self.assertIsInstance(_snake_case , _snake_case ) if FRAMEWORK != "jax": lowerCAmelCase = list(batch.input_ids.numpy()[0] ) else: lowerCAmelCase = list(batch.input_ids.tolist()[0] ) self.assertListEqual(_snake_case , _snake_case ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.ta_base_tokenizer lowerCAmelCase = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] lowerCAmelCase = tokenizer(_snake_case , padding=_snake_case , return_tensors=_snake_case ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , _snake_case ) self.assertIn('attention_mask' , _snake_case ) self.assertNotIn('decoder_input_ids' , _snake_case ) self.assertNotIn('decoder_attention_mask' , _snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.ta_base_tokenizer lowerCAmelCase = [ 'Summary of the text.', 'Another summary.', ] lowerCAmelCase = tokenizer( text_target=_snake_case , max_length=32 , padding='max_length' , truncation=_snake_case , return_tensors=_snake_case ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.ta_base_tokenizer lowerCAmelCase = ['A long paragraph for summarization. </s>'] lowerCAmelCase = ['Summary of the text. </s>'] # fmt: off lowerCAmelCase = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] lowerCAmelCase = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on lowerCAmelCase = tokenizer(_snake_case , text_target=_snake_case ) self.assertEqual(_snake_case , batch['input_ids'][0] ) self.assertEqual(_snake_case , batch['labels'][0] ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = 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 lowerCAmelCase = 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 lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = ' He is very happy, UNwant\u00E9d,running' lowerCAmelCase = tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) tokenizer.save_pretrained(_snake_case ) lowerCAmelCase = tokenizer.__class__.from_pretrained(_snake_case ) lowerCAmelCase = after_tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) self.assertListEqual(_snake_case , _snake_case ) shutil.rmtree(_snake_case ) lowerCAmelCase = 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 lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) lowerCAmelCase = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) lowerCAmelCase = tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) tokenizer.save_pretrained(_snake_case ) lowerCAmelCase = tokenizer.__class__.from_pretrained(_snake_case ) lowerCAmelCase = after_tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) self.assertListEqual(_snake_case , _snake_case ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) lowerCAmelCase = tokenizer.__class__.from_pretrained(_snake_case , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = [] 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(_snake_case ) with open(os.path.join(_snake_case , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: lowerCAmelCase = json.load(_snake_case ) with open(os.path.join(_snake_case , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: lowerCAmelCase = json.load(_snake_case ) lowerCAmelCase = [F'<extra_id_{i}>' for i in range(1_25 )] lowerCAmelCase = added_tokens_extra_ids + [ 'an_additional_special_token' ] lowerCAmelCase = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(_snake_case , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(_snake_case , _snake_case ) with open(os.path.join(_snake_case , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(_snake_case , _snake_case ) # 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 lowerCAmelCase = tokenizer_class.from_pretrained( _snake_case , ) self.assertIn( 'an_additional_special_token' , 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( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained lowerCAmelCase = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=_snake_case )] lowerCAmelCase = tokenizer_class.from_pretrained( _snake_case , additional_special_tokens=_snake_case , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = [] 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(_snake_case ) lowerCAmelCase = tokenizer_class.from_pretrained(_snake_case ) self.assertTrue(tokenizer.decode([2_55] ) == '' ) def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.get_tokenizers(fast=_snake_case , do_lower_case=_snake_case ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): lowerCAmelCase = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] lowerCAmelCase = tokenizer.convert_tokens_to_string(_snake_case ) self.assertIsInstance(_snake_case , _snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): lowerCAmelCase = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] lowerCAmelCase = 0 lowerCAmelCase = tokenizer.convert_ids_to_tokens( _snake_case , skip_special_tokens=_snake_case ) for attr in attributes_list: setattr(_snake_case , attr + '_id' , _snake_case ) self.assertEqual(getattr(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(getattr(_snake_case , attr + '_id' ) , _snake_case ) setattr(_snake_case , attr + '_id' , _snake_case ) self.assertEqual(getattr(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(getattr(_snake_case , attr + '_id' ) , _snake_case ) setattr(_snake_case , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(_snake_case , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(_snake_case , 'additional_special_tokens_ids' ) , [] ) setattr(_snake_case , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(_snake_case , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(_snake_case , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
4
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : 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 : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
0
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def A (__lowerCamelCase :int ): _lowerCAmelCase = botoa.client("""iam""" ) _lowerCAmelCase = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=__lowerCamelCase , AssumeRolePolicyDocument=json.dumps(__lowerCamelCase , indent=2 ) ) _lowerCAmelCase = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=__lowerCamelCase , PolicyName=f'{role_name}_policy_permission' , PolicyDocument=json.dumps(__lowerCamelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f'role {role_name} already exists. Using existing one' ) def A (__lowerCamelCase :List[str] ): _lowerCAmelCase = botoa.client("""iam""" ) return iam_client.get_role(RoleName=__lowerCamelCase )["Role"]["Arn"] def A (): _lowerCAmelCase = _ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , __lowerCamelCase , ) _lowerCAmelCase = None if credentials_configuration == 0: _lowerCAmelCase = _ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) _lowerCAmelCase = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) _lowerCAmelCase = _ask_field("""AWS Access Key ID: """ ) _lowerCAmelCase = aws_access_key_id _lowerCAmelCase = _ask_field("""AWS Secret Access Key: """ ) _lowerCAmelCase = aws_secret_access_key _lowerCAmelCase = _ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) _lowerCAmelCase = aws_region _lowerCAmelCase = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , __lowerCamelCase , ) if role_management == 0: _lowerCAmelCase = _ask_field("""Enter your IAM role name: """ ) else: _lowerCAmelCase = """accelerate_sagemaker_execution_role""" print(f'Accelerate will create an iam role "{iam_role_name}" using the provided credentials' ) _create_iam_role_for_sagemaker(__lowerCamelCase ) _lowerCAmelCase = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=__lowerCamelCase , error_message="""Please enter yes or no.""" , ) _lowerCAmelCase = None if is_custom_docker_image: _lowerCAmelCase = _ask_field("""Enter your Docker image: """ , lambda __lowerCamelCase : str(__lowerCamelCase ).lower() ) _lowerCAmelCase = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=__lowerCamelCase , error_message="""Please enter yes or no.""" , ) _lowerCAmelCase = None if is_sagemaker_inputs_enabled: _lowerCAmelCase = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda __lowerCamelCase : str(__lowerCamelCase ).lower() , ) _lowerCAmelCase = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=__lowerCamelCase , error_message="""Please enter yes or no.""" , ) _lowerCAmelCase = None if is_sagemaker_metrics_enabled: _lowerCAmelCase = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda __lowerCamelCase : str(__lowerCamelCase ).lower() , ) _lowerCAmelCase = _ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) _lowerCAmelCase = {} _lowerCAmelCase = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=__lowerCamelCase , error_message="""Please enter yes or no.""" , ) if use_dynamo: _lowerCAmelCase = """dynamo_""" _lowerCAmelCase = _ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) _lowerCAmelCase = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=__lowerCamelCase , error_message="""Please enter yes or no.""" , ) if use_custom_options: _lowerCAmelCase = _ask_options( """Which mode do you want to use?""" , __lowerCamelCase , lambda __lowerCamelCase : TORCH_DYNAMO_MODES[int(__lowerCamelCase )] , default="""default""" , ) _lowerCAmelCase = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=__lowerCamelCase , error_message="""Please enter yes or no.""" , ) _lowerCAmelCase = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=__lowerCamelCase , error_message="""Please enter yes or no.""" , ) _lowerCAmelCase = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: _lowerCAmelCase = _ask_options( __lowerCamelCase , __lowerCamelCase , lambda __lowerCamelCase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__lowerCamelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" _lowerCAmelCase = _ask_field(__lowerCamelCase , lambda __lowerCamelCase : str(__lowerCamelCase ).lower() , default="""ml.p3.2xlarge""" ) _lowerCAmelCase = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): _lowerCAmelCase = _ask_field( """How many machines do you want use? [1]: """ , __lowerCamelCase , default=1 , ) _lowerCAmelCase = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=__lowerCamelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=__lowerCamelCase , use_cpu=__lowerCamelCase , dynamo_config=__lowerCamelCase , eca_instance_type=__lowerCamelCase , profile=__lowerCamelCase , region=__lowerCamelCase , iam_role_name=__lowerCamelCase , mixed_precision=__lowerCamelCase , num_machines=__lowerCamelCase , sagemaker_inputs_file=__lowerCamelCase , sagemaker_metrics_file=__lowerCamelCase , )
5
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
0
import math def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Any ): if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(UpperCamelCase__ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("""This should never happen""" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. _lowerCamelCase = 'Enter the base and the power separated by a comma: ' _lowerCamelCase , _lowerCamelCase = map(int, input(prompt).split(',')) _lowerCamelCase , _lowerCamelCase = map(int, input(prompt).split(',')) # We find the log of each number, using the function res(), which takes two # arguments. _lowerCamelCase = res(xa, ya) _lowerCamelCase = res(xa, ya) # We check for the largest number if resa > resa: print('Largest number is', xa, '^', ya) elif resa > resa: print('Largest number is', xa, '^', ya) else: print('Both are equal')
6
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __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 a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
0
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py a = '''src/transformers''' a = '''docs/source/en''' a = '''.''' def _snake_case ( _snake_case : Tuple , _snake_case : Dict , _snake_case : Tuple ) -> Optional[Any]: '''simple docstring''' with open(_snake_case , 'r' , encoding='utf-8' , newline='\n' ) as f: _A = f.readlines() # Find the start prompt. _A = 0 while not lines[start_index].startswith(_snake_case ): start_index += 1 start_index += 1 _A = start_index while not lines[end_index].startswith(_snake_case ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | a = '''Model|Encoder|Decoder|ForConditionalGeneration''' # Regexes that match TF/Flax/PT model names. a = re.compile(r'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') a = re.compile(r'''Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. a = re.compile(r'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # This is to make sure the transformers module imported is the one in the repo. a = direct_transformers_import(TRANSFORMERS_PATH) def _snake_case ( _snake_case : Dict ) -> List[str]: '''simple docstring''' _A = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , _snake_case ) return [m.group(0 ) for m in matches] def _snake_case ( _snake_case : str , _snake_case : Any ) -> int: '''simple docstring''' _A = 2 if text == '✅' or text == '❌' else len(_snake_case ) _A = (width - text_length) // 2 _A = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _snake_case ( ) -> Optional[Any]: '''simple docstring''' _A = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _A = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } _A = {name: config.replace('Config' , '' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. _A = collections.defaultdict(_snake_case ) _A = collections.defaultdict(_snake_case ) _A = collections.defaultdict(_snake_case ) _A = collections.defaultdict(_snake_case ) _A = collections.defaultdict(_snake_case ) # Let's lookup through all transformers object (once). for attr_name in dir(_snake_case ): _A = None if attr_name.endswith('Tokenizer' ): _A = slow_tokenizers _A = attr_name[:-9] elif attr_name.endswith('TokenizerFast' ): _A = fast_tokenizers _A = attr_name[:-13] elif _re_tf_models.match(_snake_case ) is not None: _A = tf_models _A = _re_tf_models.match(_snake_case ).groups()[0] elif _re_flax_models.match(_snake_case ) is not None: _A = flax_models _A = _re_flax_models.match(_snake_case ).groups()[0] elif _re_pt_models.match(_snake_case ) is not None: _A = pt_models _A = _re_pt_models.match(_snake_case ).groups()[0] if lookup_dict is not None: while len(_snake_case ) > 0: if attr_name in model_name_to_prefix.values(): _A = True break # Try again after removing the last word in the name _A = ''.join(camel_case_split(_snake_case )[:-1] ) # Let's build that table! _A = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) _A = ['Model', 'Tokenizer slow', 'Tokenizer fast', 'PyTorch support', 'TensorFlow support', 'Flax Support'] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). _A = [len(_snake_case ) + 2 for c in columns] _A = max([len(_snake_case ) for name in model_names] ) + 2 # Build the table per se _A = '|' + '|'.join([_center_text(_snake_case , _snake_case ) for c, w in zip(_snake_case , _snake_case )] ) + '|\n' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([':' + '-' * (w - 2) + ':' for w in widths] ) + "|\n" _A = {True: '✅', False: '❌'} for name in model_names: _A = model_name_to_prefix[name] _A = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_snake_case , _snake_case ) for l, w in zip(_snake_case , _snake_case )] ) + "|\n" return table def _snake_case ( _snake_case : List[str]=False ) -> Union[str, Any]: '''simple docstring''' _A , _A , _A , _A = _find_text_in_file( filename=os.path.join(_snake_case , 'index.md' ) , start_prompt='<!--This table is updated automatically from the auto modules' , end_prompt='<!-- End table-->' , ) _A = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_snake_case , 'index.md' ) , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( 'The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.' ) if __name__ == "__main__": a = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') a = parser.parse_args() check_model_table(args.fix_and_overwrite)
7
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class SCREAMING_SNAKE_CASE (a__ ): lowerCAmelCase = 42 class SCREAMING_SNAKE_CASE (a__ , a__ ): @register_to_config def __init__( self , _UpperCAmelCase = 3 , _UpperCAmelCase = 3 , _UpperCAmelCase = ("DownEncoderBlock2D",) , _UpperCAmelCase = ("UpDecoderBlock2D",) , _UpperCAmelCase = (64,) , _UpperCAmelCase = 1 , _UpperCAmelCase = "silu" , _UpperCAmelCase = 3 , _UpperCAmelCase = 32 , _UpperCAmelCase = 256 , _UpperCAmelCase = 32 , _UpperCAmelCase = None , _UpperCAmelCase = 0.18215 , _UpperCAmelCase = "group" , ): '''simple docstring''' super().__init__() # pass init params to Encoder __A : Optional[int] = Encoder( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , down_block_types=_UpperCAmelCase , block_out_channels=_UpperCAmelCase , layers_per_block=_UpperCAmelCase , act_fn=_UpperCAmelCase , norm_num_groups=_UpperCAmelCase , double_z=_UpperCAmelCase , ) __A : Dict = vq_embed_dim if vq_embed_dim is not None else latent_channels __A : Union[str, Any] = nn.Convad(_UpperCAmelCase , _UpperCAmelCase , 1) __A : List[Any] = VectorQuantizer(_UpperCAmelCase , _UpperCAmelCase , beta=0.25 , remap=_UpperCAmelCase , sane_index_shape=_UpperCAmelCase) __A : Dict = nn.Convad(_UpperCAmelCase , _UpperCAmelCase , 1) # pass init params to Decoder __A : Any = Decoder( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , up_block_types=_UpperCAmelCase , block_out_channels=_UpperCAmelCase , layers_per_block=_UpperCAmelCase , act_fn=_UpperCAmelCase , norm_num_groups=_UpperCAmelCase , norm_type=_UpperCAmelCase , ) @apply_forward_hook def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = True): '''simple docstring''' __A : Optional[int] = self.encoder(_UpperCAmelCase) __A : str = self.quant_conv(_UpperCAmelCase) if not return_dict: return (h,) return VQEncoderOutput(latents=_UpperCAmelCase) @apply_forward_hook def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = False , _UpperCAmelCase = True): '''simple docstring''' if not force_not_quantize: __A ,__A ,__A : Dict = self.quantize(_UpperCAmelCase) else: __A : int = h __A : List[Any] = self.post_quant_conv(_UpperCAmelCase) __A : Union[str, Any] = self.decoder(_UpperCAmelCase , quant if self.config.norm_type == 'spatial' else None) if not return_dict: return (dec,) return DecoderOutput(sample=_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = True): '''simple docstring''' __A : Any = sample __A : Optional[int] = self.encode(_UpperCAmelCase).latents __A : Union[str, Any] = self.decode(_UpperCAmelCase).sample if not return_dict: return (dec,) return DecoderOutput(sample=_UpperCAmelCase)
8
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
0
SCREAMING_SNAKE_CASE__ = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' SCREAMING_SNAKE_CASE__ = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] SCREAMING_SNAKE_CASE__ = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
9
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
0
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : def __init__( self : Any , _A : int , _A : int=12 , _A : int=7 , _A : Tuple=True , _A : Optional[int]=True , _A : Union[str, Any]=True , _A : str=99 , _A : str=32 , _A : int=32 , _A : Optional[Any]=2 , _A : Dict=4 , _A : int=37 , _A : List[Any]=0.1 , _A : str=0.1 , _A : Any=512 , _A : int=0.02 , _A : Optional[Any]=0 , _A : Dict=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = projection_dim _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = dropout _UpperCamelCase = attention_dropout _UpperCamelCase = max_position_embeddings _UpperCamelCase = initializer_range _UpperCamelCase = scope _UpperCamelCase = bos_token_id def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: _UpperCamelCase = input_mask.numpy() _UpperCamelCase , _UpperCamelCase = input_mask.shape _UpperCamelCase = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_A ): _UpperCamelCase = 1 _UpperCamelCase = 0 _UpperCamelCase = self.get_config() return config, input_ids, tf.convert_to_tensor(_A ) def UpperCamelCase_ ( self : str ): return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def UpperCamelCase_ ( self : List[str] , _A : Tuple , _A : str , _A : Optional[Any] ): _UpperCamelCase = TFBlipTextModel(config=_A ) _UpperCamelCase = model(_A , attention_mask=_A , training=_A ) _UpperCamelCase = model(_A , training=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, unittest.TestCase ): UpperCAmelCase = (TFBlipTextModel,) if is_tf_available() else () UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = BlipTextModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : Dict ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : List[Any] ): pass def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason='''Blip does not use inputs_embeds''' ) def UpperCamelCase_ ( self : Dict ): pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase_ ( self : Dict ): pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase_ ( self : List[str] ): pass @slow def UpperCamelCase_ ( self : Optional[int] ): for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = TFBlipTextModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def UpperCamelCase_ ( self : int , _A : Optional[int]=True ): super().test_pt_tf_model_equivalence(allow_missing_keys=_A )
10
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
0
'''simple docstring''' import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __A : '''simple docstring''' def __init__(self , A , A=2 , A=3 , A=4 , A=2 , A=7 , A=True , A=True , A=True , A=True , A=99 , A=36 , A=3 , A=4 , A=37 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=16 , A=2 , A=0.02 , A=6 , A=6 , A=3 , A=4 , A=None , A=1_000 , ) -> List[str]: """simple docstring""" _a = parent _a = batch_size _a = num_channels _a = image_size _a = patch_size _a = text_seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = coordinate_size _a = shape_size _a = num_labels _a = num_choices _a = scope _a = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _a = text_seq_length _a = (image_size // patch_size) ** 2 + 1 _a = self.text_seq_length + self.image_seq_length def a__ (self ) -> Optional[int]: """simple docstring""" _a = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _a = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: _a = bbox[i, j, 3] _a = bbox[i, j, 1] _a = t if bbox[i, j, 2] < bbox[i, j, 0]: _a = bbox[i, j, 2] _a = bbox[i, j, 0] _a = t _a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.text_seq_length] ) _a = None if self.use_token_type_ids: _a = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _a = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def a__ (self , A , A , A , A , A , A , A , A ) -> List[str]: """simple docstring""" _a = LayoutLMvaModel(config=A ) model.to(A ) model.eval() # text + image _a = model(A , pixel_values=A ) _a = model( A , bbox=A , pixel_values=A , attention_mask=A , token_type_ids=A ) _a = model(A , bbox=A , pixel_values=A , token_type_ids=A ) _a = model(A , bbox=A , pixel_values=A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _a = model(A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _a = model(pixel_values=A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def a__ (self , A , A , A , A , A , A , A , A ) -> Tuple: """simple docstring""" _a = self.num_labels _a = LayoutLMvaForSequenceClassification(A ) model.to(A ) model.eval() _a = model( A , bbox=A , pixel_values=A , attention_mask=A , token_type_ids=A , labels=A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ (self , A , A , A , A , A , A , A , A ) -> Optional[Any]: """simple docstring""" _a = self.num_labels _a = LayoutLMvaForTokenClassification(config=A ) model.to(A ) model.eval() _a = model( A , bbox=A , pixel_values=A , attention_mask=A , token_type_ids=A , labels=A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def a__ (self , A , A , A , A , A , A , A , A ) -> Any: """simple docstring""" _a = LayoutLMvaForQuestionAnswering(config=A ) model.to(A ) model.eval() _a = model( A , bbox=A , pixel_values=A , attention_mask=A , token_type_ids=A , start_positions=A , end_positions=A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a__ (self ) -> int: """simple docstring""" _a = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) = config_and_inputs _a = { '''input_ids''': input_ids, '''bbox''': bbox, '''pixel_values''': pixel_values, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __A ( A , A , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Optional[int] = False __lowerCamelCase : int = False __lowerCamelCase : int = False __lowerCamelCase : List[str] = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) __lowerCamelCase : List[str] = ( {'document-question-answering': LayoutLMvaForQuestionAnswering, 'feature-extraction': LayoutLMvaModel} if is_torch_available() else {} ) def a__ (self , A , A , A , A , A ) -> Dict: """simple docstring""" return True def a__ (self ) -> Dict: """simple docstring""" _a = LayoutLMvaModelTester(self ) _a = ConfigTester(self , config_class=A , hidden_size=37 ) def a__ (self , A , A , A=False ) -> List[str]: """simple docstring""" _a = copy.deepcopy(A ) if model_class in get_values(A ): _a = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(A , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A ): _a = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=A ) elif model_class in get_values(A ): _a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A ) _a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A ) elif model_class in [ *get_values(A ), ]: _a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A ) elif model_class in [ *get_values(A ), ]: _a = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=A , ) return inputs_dict def a__ (self ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def a__ (self ) -> Optional[Any]: """simple docstring""" _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def a__ (self ) -> Tuple: """simple docstring""" _a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a = type self.model_tester.create_and_check_model(*A ) def a__ (self ) -> List[str]: """simple docstring""" _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def a__ (self ) -> List[str]: """simple docstring""" _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) def a__ (self ) -> List[Any]: """simple docstring""" _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) @slow def a__ (self ) -> List[Any]: """simple docstring""" for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = LayoutLMvaModel.from_pretrained(A ) self.assertIsNotNone(A ) def lowerCAmelCase (): """simple docstring""" _a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''') return image @require_torch class __A ( unittest.TestCase ): '''simple docstring''' @cached_property def a__ (self ) -> Optional[int]: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=A ) if is_vision_available() else None @slow def a__ (self ) -> Any: """simple docstring""" _a = LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' ).to(A ) _a = self.default_image_processor _a = prepare_img() _a = image_processor(images=A , return_tensors='''pt''' ).pixel_values.to(A ) _a = torch.tensor([[1, 2]] ) _a = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass _a = model( input_ids=input_ids.to(A ) , bbox=bbox.to(A ) , pixel_values=pixel_values.to(A ) , ) # verify the logits _a = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , A ) _a = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , A , atol=1E-4 ) )
11
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
0
def UpperCamelCase ( lowercase_ ) -> set: '''simple docstring''' lowercase__ : Optional[Any] = set() # edges = list of graph's edges lowercase__ : List[Any] = get_edges(lowercase_ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: lowercase__ , lowercase__ : Union[str, Any] = edges.pop() chosen_vertices.add(lowercase_ ) chosen_vertices.add(lowercase_ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(lowercase_ ) return chosen_vertices def UpperCamelCase ( lowercase_ ) -> set: '''simple docstring''' lowercase__ : Tuple = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
12
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
0
'''simple docstring''' import requests from bsa import BeautifulSoup def UpperCAmelCase__ ( UpperCAmelCase_ : str = "AAPL" ) -> str: __lowerCamelCase : str = F'https://in.finance.yahoo.com/quote/{symbol}?s={symbol}' __lowerCamelCase : Optional[int] = BeautifulSoup(requests.get(UpperCAmelCase_ ).text , 'html.parser' ) __lowerCamelCase : Optional[Any] = 'My(6px) Pos(r) smartphone_Mt(6px)' return soup.find('div' , class_=class_ ).find('span' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
13
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = 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 flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
0
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() a__ = logging.get_logger(__name__) a__ = [ ['''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 ( __a : Any ) -> Union[str, Any]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: _a : List[Any] = k.replace(__a ,__a ) if k.startswith('''encoder''' ): _a : Dict = k.replace('''.attn''' ,'''.self_attn''' ) _a : Optional[int] = k.replace('''norm1''' ,'''self_attn_layer_norm''' ) _a : Union[str, Any] = k.replace('''norm2''' ,'''final_layer_norm''' ) elif k.startswith('''decoder''' ): _a : int = k.replace('''norm1''' ,'''self_attn_layer_norm''' ) _a : Any = k.replace('''norm2''' ,'''encoder_attn_layer_norm''' ) _a : List[Any] = k.replace('''norm3''' ,'''final_layer_norm''' ) return k def __UpperCAmelCase ( __a : Union[str, Any] ) -> List[Any]: """simple docstring""" _a : List[str] = [ '''model.encoder.layernorm_embedding.weight''', '''model.encoder.layernorm_embedding.bias''', '''model.decoder.layernorm_embedding.weight''', '''model.decoder.layernorm_embedding.bias''', ] for k in keys: _a : List[str] = sd.pop(__a ) _a : Any = k.replace('''layernorm_embedding''' ,'''layer_norm''' ) assert new_k not in sd _a : str = v a__ = ['''START'''] @torch.no_grad() def __UpperCAmelCase ( __a : Union[str, Any] ,__a : str ,__a : Union[str, Any] ) -> str: """simple docstring""" _a : Optional[Any] = torch.load(__a ,map_location='''cpu''' ) _a : Optional[int] = model['''model'''] _a : Tuple = BlenderbotConfig.from_json_file(__a ) _a : Tuple = BlenderbotForConditionalGeneration(__a ) _a : Union[str, Any] = m.model.state_dict().keys() _a : str = [] _a : Optional[int] = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue _a : str = rename_state_dict_key(__a ) if new_k not in valid_keys: failures.append([k, new_k] ) else: _a : int = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(__a ) m.model.load_state_dict(__a ,strict=__a ) m.half() m.save_pretrained(__a ) if __name__ == "__main__": a__ = 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__ = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
14
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
0
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' A__ = KandinskyVaaControlnetImgaImgPipeline A__ = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint'''] A__ = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint'''] A__ = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] A__ = False @property def lowerCamelCase__ (self : Tuple ) -> int: """simple docstring""" return 32 @property def lowerCamelCase__ (self : Optional[int] ) -> List[Any]: """simple docstring""" return 32 @property def lowerCamelCase__ (self : Union[str, Any] ) -> str: """simple docstring""" return self.time_input_dim @property def lowerCamelCase__ (self : Any ) -> List[Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCamelCase__ (self : List[str] ) -> Any: """simple docstring""" return 100 @property def lowerCamelCase__ (self : Optional[int] ) -> str: """simple docstring""" torch.manual_seed(0 ) lowercase__ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } lowercase__ = UNetaDConditionModel(**_UpperCAmelCase ) return model @property def lowerCamelCase__ (self : Dict ) -> List[str]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCamelCase__ (self : Any ) -> Dict: """simple docstring""" torch.manual_seed(0 ) lowercase__ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCamelCase__ (self : Tuple ) -> str: """simple docstring""" lowercase__ = self.dummy_unet lowercase__ = self.dummy_movq lowercase__ = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.00_085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } lowercase__ = DDIMScheduler(**_UpperCAmelCase ) lowercase__ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCamelCase__ (self : str , _UpperCAmelCase : List[str] , _UpperCAmelCase : int=0 ) -> Dict: """simple docstring""" lowercase__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) lowercase__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _UpperCAmelCase ) # create init_image lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) lowercase__ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowercase__ = Image.fromarray(np.uinta(_UpperCAmelCase ) ).convert("""RGB""" ).resize((256, 256) ) # create hint lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) if str(_UpperCAmelCase ).startswith("""mps""" ): lowercase__ = torch.manual_seed(_UpperCAmelCase ) else: lowercase__ = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) lowercase__ = { """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def lowerCamelCase__ (self : int ) -> List[str]: """simple docstring""" lowercase__ = """cpu""" lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**_UpperCAmelCase ) lowercase__ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) lowercase__ = pipe(**self.get_dummy_inputs(_UpperCAmelCase ) ) lowercase__ = output.images lowercase__ = pipe( **self.get_dummy_inputs(_UpperCAmelCase ) , return_dict=_UpperCAmelCase , )[0] lowercase__ = image[0, -3:, -3:, -1] lowercase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowercase__ = np.array( [0.54_985_034, 0.55_509_365, 0.52_561_504, 0.5_570_494, 0.5_593_818, 0.5_263_979, 0.50_285_643, 0.5_069_846, 0.51_196_736] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class A ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase__ (self : List[str] ) -> Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ (self : List[Any] ) -> List[Any]: """simple docstring""" lowercase__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy""" ) lowercase__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) lowercase__ = init_image.resize((512, 512) ) lowercase__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) lowercase__ = torch.from_numpy(np.array(_UpperCAmelCase ) ).float() / 255.0 lowercase__ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) lowercase__ = """A robot, 4k photo""" lowercase__ = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_UpperCAmelCase ) lowercase__ = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) lowercase__ = pipeline.to(_UpperCAmelCase ) pipeline.set_progress_bar_config(disable=_UpperCAmelCase ) lowercase__ = torch.Generator(device="""cpu""" ).manual_seed(0 ) lowercase__ , lowercase__ = pipe_prior( _UpperCAmelCase , image=_UpperCAmelCase , strength=0.85 , generator=_UpperCAmelCase , negative_prompt="""""" , ).to_tuple() lowercase__ = pipeline( image=_UpperCAmelCase , image_embeds=_UpperCAmelCase , negative_image_embeds=_UpperCAmelCase , hint=_UpperCAmelCase , generator=_UpperCAmelCase , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type="""np""" , ) lowercase__ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(_UpperCAmelCase , _UpperCAmelCase )
15
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
0
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowerCamelCase__ = LEDConfig lowerCamelCase__ = {} lowerCamelCase__ = "gelu" def __init__( self : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str]=13 , __lowerCamelCase : str=7 , __lowerCamelCase : Any=True , __lowerCamelCase : str=False , __lowerCamelCase : Optional[Any]=99 , __lowerCamelCase : Any=32 , __lowerCamelCase : Tuple=2 , __lowerCamelCase : str=4 , __lowerCamelCase : Optional[int]=37 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=20 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : Dict=4 , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training 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_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = eos_token_id SCREAMING_SNAKE_CASE = pad_token_id SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after SCREAMING_SNAKE_CASE = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests SCREAMING_SNAKE_CASE = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) SCREAMING_SNAKE_CASE = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) SCREAMING_SNAKE_CASE = tf.concat([input_ids, eos_tensor] , axis=1 ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) SCREAMING_SNAKE_CASE = prepare_led_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = tf.concat( [tf.zeros_like(__lowerCamelCase )[:, :-1], tf.ones_like(__lowerCamelCase )[:, -1:]] , axis=-1 , ) SCREAMING_SNAKE_CASE = global_attention_mask return config, inputs_dict def _snake_case ( self : int , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] ): SCREAMING_SNAKE_CASE = TFLEDModel(config=__lowerCamelCase ).get_decoder() SCREAMING_SNAKE_CASE = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE = input_ids[:1, :] SCREAMING_SNAKE_CASE = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE = 1 # first forward pass SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE = tf.concat([input_ids, next_tokens] , axis=-1 ) SCREAMING_SNAKE_CASE = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1e-3 ) def __a ( A__ : int , A__ : Dict , A__ : List[str] , A__ : int=None , A__ : List[Any]=None , A__ : Optional[int]=None , A__ : Dict=None , ): if attention_mask is None: SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(A__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () lowerCamelCase__ = (TFLEDForConditionalGeneration,) if is_tf_available() else () lowerCamelCase__ = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) lowerCamelCase__ = True lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = TFLEDModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase ) def _snake_case ( self : Tuple ): self.config_tester.run_common_tests() def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = tf.zeros_like(inputs_dict["attention_mask"] ) SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model_tester.seq_length SCREAMING_SNAKE_CASE = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__lowerCamelCase : Tuple ): SCREAMING_SNAKE_CASE = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__lowerCamelCase : Dict ): SCREAMING_SNAKE_CASE = [t.numpy() for t in outputs.encoder_attentions] SCREAMING_SNAKE_CASE = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def _snake_case ( self : List[Any] ): pass def _snake_case ( self : List[str] ): # TODO: Head-masking not yet implement pass def __a ( A__ : Any ): return tf.constant(A__ , dtype=tf.intaa ) __A : Optional[int] = 1e-4 @slow @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here SCREAMING_SNAKE_CASE = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) SCREAMING_SNAKE_CASE = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) SCREAMING_SNAKE_CASE = prepare_led_inputs_dict(model.config , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase )[0] SCREAMING_SNAKE_CASE = (1, 1024, 768) self.assertEqual(output.shape , __lowerCamelCase ) # change to expected output here SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1e-3 ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here SCREAMING_SNAKE_CASE = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) SCREAMING_SNAKE_CASE = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) SCREAMING_SNAKE_CASE = prepare_led_inputs_dict(model.config , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**__lowerCamelCase )[0] SCREAMING_SNAKE_CASE = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __lowerCamelCase ) # change to expected output here SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1e-3 , rtol=1e-3 )
16
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
0
from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class lowerCamelCase_ ( nn.Module ): def __init__( self : Tuple , __A : int , __A : int , __A : int , __A : str=0.0 , __A : Optional[int] = None , __A : str = "geglu" , __A : Optional[int] = None , __A : bool = False , __A : bool = False , __A : bool = False , __A : bool = False , __A : bool = True , __A : str = "layer_norm" , __A : bool = False , ): super().__init__() __A : Any = only_cross_attention __A : Dict = (num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero""" __A : Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == """ada_norm""" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: __A : str = AdaLayerNorm(__A , __A ) elif self.use_ada_layer_norm_zero: __A : Dict = AdaLayerNormZero(__A , __A ) else: __A : Optional[int] = nn.LayerNorm(__A , elementwise_affine=__A ) __A : List[str] = Attention( query_dim=__A , heads=__A , dim_head=__A , dropout=__A , bias=__A , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__A , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. __A : Optional[Any] = ( AdaLayerNorm(__A , __A ) if self.use_ada_layer_norm else nn.LayerNorm(__A , elementwise_affine=__A ) ) __A : Any = Attention( query_dim=__A , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__A , dim_head=__A , dropout=__A , bias=__A , upcast_attention=__A , ) # is self-attn if encoder_hidden_states is none else: __A : str = None __A : int = None # 3. Feed-forward __A : Optional[int] = nn.LayerNorm(__A , elementwise_affine=__A ) __A : Dict = FeedForward(__A , dropout=__A , activation_fn=__A , final_dropout=__A ) # let chunk size default to None __A : List[Any] = None __A : Union[str, Any] = 0 def lowerCAmelCase_ ( self : List[str] , __A : Optional[int] , __A : int ): # Sets chunk feed-forward __A : str = chunk_size __A : List[str] = dim def lowerCAmelCase_ ( self : Optional[int] , __A : torch.FloatTensor , __A : Optional[torch.FloatTensor] = None , __A : Optional[torch.FloatTensor] = None , __A : Optional[torch.FloatTensor] = None , __A : Optional[torch.LongTensor] = None , __A : Dict[str, Any] = None , __A : Optional[torch.LongTensor] = None , ): # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: __A : Tuple = self.norma(__A , __A ) elif self.use_ada_layer_norm_zero: __A , __A , __A , __A , __A : Union[str, Any] = self.norma( __A , __A , __A , hidden_dtype=hidden_states.dtype ) else: __A : List[str] = self.norma(__A ) __A : Tuple = cross_attention_kwargs if cross_attention_kwargs is not None else {} __A : Optional[int] = self.attna( __A , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__A , **__A , ) if self.use_ada_layer_norm_zero: __A : List[Any] = gate_msa.unsqueeze(1 ) * attn_output __A : Optional[int] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: __A : Union[str, Any] = ( self.norma(__A , __A ) if self.use_ada_layer_norm else self.norma(__A ) ) __A : Tuple = self.attna( __A , encoder_hidden_states=__A , attention_mask=__A , **__A , ) __A : Union[str, Any] = attn_output + hidden_states # 3. Feed-forward __A : Tuple = self.norma(__A ) if self.use_ada_layer_norm_zero: __A : Tuple = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) __A : str = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size __A : List[str] = torch.cat( [self.ff(__A ) for hid_slice in norm_hidden_states.chunk(__A , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: __A : List[Any] = self.ff(__A ) if self.use_ada_layer_norm_zero: __A : List[Any] = gate_mlp.unsqueeze(1 ) * ff_output __A : Any = ff_output + hidden_states return hidden_states class lowerCamelCase_ ( nn.Module ): def __init__( self : Union[str, Any] , __A : int , __A : Optional[int] = None , __A : int = 4 , __A : float = 0.0 , __A : str = "geglu" , __A : bool = False , ): super().__init__() __A : Any = int(dim * mult ) __A : Optional[int] = dim_out if dim_out is not None else dim if activation_fn == "gelu": __A : Tuple = GELU(__A , __A ) if activation_fn == "gelu-approximate": __A : int = GELU(__A , __A , approximate="""tanh""" ) elif activation_fn == "geglu": __A : List[str] = GEGLU(__A , __A ) elif activation_fn == "geglu-approximate": __A : Any = ApproximateGELU(__A , __A ) __A : Optional[int] = nn.ModuleList([] ) # project in self.net.append(__A ) # project dropout self.net.append(nn.Dropout(__A ) ) # project out self.net.append(nn.Linear(__A , __A ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(__A ) ) def lowerCAmelCase_ ( self : Any , __A : Union[str, Any] ): for module in self.net: __A : List[Any] = module(__A ) return hidden_states class lowerCamelCase_ ( nn.Module ): def __init__( self : Optional[Any] , __A : int , __A : int , __A : str = "none" ): super().__init__() __A : Dict = nn.Linear(__A , __A ) __A : List[Any] = approximate def lowerCAmelCase_ ( self : str , __A : Optional[Any] ): if gate.device.type != "mps": return F.gelu(__A , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def lowerCAmelCase_ ( self : List[Any] , __A : Optional[int] ): __A : Union[str, Any] = self.proj(__A ) __A : Tuple = self.gelu(__A ) return hidden_states class lowerCamelCase_ ( nn.Module ): def __init__( self : Union[str, Any] , __A : int , __A : int ): super().__init__() __A : Optional[int] = nn.Linear(__A , dim_out * 2 ) def lowerCAmelCase_ ( self : Tuple , __A : Tuple ): if gate.device.type != "mps": return F.gelu(__A ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def lowerCAmelCase_ ( self : int , __A : Dict ): __A , __A : Dict = self.proj(__A ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(__A ) class lowerCamelCase_ ( nn.Module ): def __init__( self : Optional[Any] , __A : int , __A : int ): super().__init__() __A : Tuple = nn.Linear(__A , __A ) def lowerCAmelCase_ ( self : int , __A : Tuple ): __A : List[str] = self.proj(__A ) return x * torch.sigmoid(1.7_0_2 * x ) class lowerCamelCase_ ( nn.Module ): def __init__( self : int , __A : str , __A : str ): super().__init__() __A : Optional[Any] = nn.Embedding(__A , __A ) __A : Any = nn.SiLU() __A : Optional[Any] = nn.Linear(__A , embedding_dim * 2 ) __A : Optional[int] = nn.LayerNorm(__A , elementwise_affine=__A ) def lowerCAmelCase_ ( self : str , __A : Any , __A : Tuple ): __A : List[Any] = self.linear(self.silu(self.emb(__A ) ) ) __A , __A : Union[str, Any] = torch.chunk(__A , 2 ) __A : str = self.norm(__A ) * (1 + scale) + shift return x class lowerCamelCase_ ( nn.Module ): def __init__( self : Tuple , __A : Union[str, Any] , __A : int ): super().__init__() __A : Any = CombinedTimestepLabelEmbeddings(__A , __A ) __A : Any = nn.SiLU() __A : Tuple = nn.Linear(__A , 6 * embedding_dim , bias=__A ) __A : Union[str, Any] = nn.LayerNorm(__A , elementwise_affine=__A , eps=1e-6 ) def lowerCAmelCase_ ( self : Tuple , __A : Any , __A : Union[str, Any] , __A : Dict , __A : Optional[int]=None ): __A : Tuple = self.linear(self.silu(self.emb(__A , __A , hidden_dtype=__A ) ) ) __A , __A , __A , __A , __A , __A : List[Any] = emb.chunk(6 , dim=1 ) __A : str = self.norm(__A ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class lowerCamelCase_ ( nn.Module ): def __init__( self : Dict , __A : int , __A : int , __A : int , __A : Optional[str] = None , __A : float = 1e-5 ): super().__init__() __A : Optional[Any] = num_groups __A : Tuple = eps if act_fn is None: __A : Union[str, Any] = None else: __A : Tuple = get_activation(__A ) __A : Optional[Any] = nn.Linear(__A , out_dim * 2 ) def lowerCAmelCase_ ( self : List[Any] , __A : List[Any] , __A : Optional[int] ): if self.act: __A : Union[str, Any] = self.act(__A ) __A : List[Any] = self.linear(__A ) __A : Dict = emb[:, :, None, None] __A , __A : str = emb.chunk(2 , dim=1 ) __A : str = F.group_norm(__A , self.num_groups , eps=self.eps ) __A : Any = x * (1 + scale) + shift return x
17
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class lowerCAmelCase_ ( __magic_name__ ): __lowerCamelCase : Union[str, Any] = "swinv2" __lowerCamelCase : int = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , _lowerCAmelCase=224 , _lowerCAmelCase=4 , _lowerCAmelCase=3 , _lowerCAmelCase=96 , _lowerCAmelCase=[2, 2, 6, 2] , _lowerCAmelCase=[3, 6, 12, 24] , _lowerCAmelCase=7 , _lowerCAmelCase=4.0 , _lowerCAmelCase=True , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.1 , _lowerCAmelCase="gelu" , _lowerCAmelCase=False , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-5 , _lowerCAmelCase=32 , **_lowerCAmelCase , ) -> Tuple: super().__init__(**_lowerCAmelCase ) _lowerCAmelCase = image_size _lowerCAmelCase = patch_size _lowerCAmelCase = num_channels _lowerCAmelCase = embed_dim _lowerCAmelCase = depths _lowerCAmelCase = len(_lowerCAmelCase ) _lowerCAmelCase = num_heads _lowerCAmelCase = window_size _lowerCAmelCase = mlp_ratio _lowerCAmelCase = qkv_bias _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = drop_path_rate _lowerCAmelCase = hidden_act _lowerCAmelCase = use_absolute_embeddings _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range _lowerCAmelCase = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase = int(embed_dim * 2 ** (len(_lowerCAmelCase ) - 1) ) _lowerCAmelCase = (0, 0, 0, 0)
18
'''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 __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = 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] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _a = logging.get_logger(__name__) _a = """▁""" _a = {"""vocab_file""": """sentencepiece.bpe.model"""} _a = { """vocab_file""": { """facebook/mbart-large-en-ro""": ( """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model""" ), """facebook/mbart-large-cc25""": ( """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model""" ), } } _a = { """facebook/mbart-large-en-ro""": 1024, """facebook/mbart-large-cc25""": 1024, } # fmt: off _a = ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""] class _UpperCAmelCase( lowerCamelCase ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = ['input_ids', 'attention_mask'] lowercase__ = [] lowercase__ = [] def __init__( self , __a , __a="<s>" , __a="</s>" , __a="</s>" , __a="<s>" , __a="<unk>" , __a="<pad>" , __a="<mask>" , __a=None , __a=None , __a=None , __a = None , __a=None , **__a , ) -> Optional[Any]: '''simple docstring''' # Mask token behave like a normal word, i.e. include the space before it _UpperCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else mask_token _UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , cls_token=__a , pad_token=__a , mask_token=__a , tokenizer_file=__a , src_lang=__a , tgt_lang=__a , additional_special_tokens=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(__a)) _UpperCamelCase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token _UpperCamelCase = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab _UpperCamelCase = 1 _UpperCamelCase = len(self.sp_model) _UpperCamelCase = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__a) } _UpperCamelCase = {v: k for k, v in self.lang_code_to_id.items()} _UpperCamelCase = len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id) _UpperCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _UpperCamelCase = list(self.lang_code_to_id.keys()) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens]) _UpperCamelCase = src_lang if src_lang is not None else '''en_XX''' _UpperCamelCase = self.lang_code_to_id[self._src_lang] _UpperCamelCase = tgt_lang self.set_src_lang_special_tokens(self._src_lang) def __getstate__( self) -> Optional[int]: '''simple docstring''' _UpperCamelCase = self.__dict__.copy() _UpperCamelCase = None _UpperCamelCase = self.sp_model.serialized_model_proto() return state def __setstate__( self , __a) -> int: '''simple docstring''' _UpperCamelCase = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): _UpperCamelCase = {} _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) @property def UpperCAmelCase ( self) -> Dict: '''simple docstring''' return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def UpperCAmelCase ( self) -> str: '''simple docstring''' return self._src_lang @src_lang.setter def UpperCAmelCase ( self , __a) -> None: '''simple docstring''' _UpperCamelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang) def UpperCAmelCase ( self , __a , __a = None , __a = False) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a) _UpperCamelCase = [1] * len(self.prefix_tokens) _UpperCamelCase = [1] * len(self.suffix_tokens) if token_ids_a is None: return prefix_ones + ([0] * len(__a)) + suffix_ones return prefix_ones + ([0] * len(__a)) + ([0] * len(__a)) + suffix_ones def UpperCAmelCase ( self , __a , __a = None) -> List[int]: '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCAmelCase ( self , __a , __a = None) -> List[int]: '''simple docstring''' _UpperCamelCase = [self.sep_token_id] _UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0] def UpperCAmelCase ( self , __a , __a , __a , __a , **__a) -> List[Any]: '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''') _UpperCamelCase = src_lang _UpperCamelCase = self(__a , add_special_tokens=__a , return_tensors=__a , **__a) _UpperCamelCase = self.convert_tokens_to_ids(__a) _UpperCamelCase = tgt_lang_id return inputs def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = {self.convert_ids_to_tokens(__a): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def UpperCAmelCase ( self , __a) -> List[str]: '''simple docstring''' return self.sp_model.encode(__a , out_type=__a) def UpperCAmelCase ( self , __a) -> List[Any]: '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _UpperCamelCase = self.sp_model.PieceToId(__a) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def UpperCAmelCase ( self , __a) -> Union[str, Any]: '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def UpperCAmelCase ( self , __a) -> int: '''simple docstring''' _UpperCamelCase = ''''''.join(__a).replace(__a , ''' ''').strip() return out_string def UpperCAmelCase ( self , __a , __a = None) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(__a): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''') return _UpperCamelCase = 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: _UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(__a) return (out_vocab_file,) def UpperCAmelCase ( self , __a , __a = "en_XX" , __a = None , __a = "ro_RO" , **__a , ) -> BatchEncoding: '''simple docstring''' _UpperCamelCase = src_lang _UpperCamelCase = tgt_lang return super().prepare_seqaseq_batch(__a , __a , **__a) def UpperCAmelCase ( self) -> str: '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang) def UpperCAmelCase ( self) -> str: '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang) def UpperCAmelCase ( self , __a) -> None: '''simple docstring''' _UpperCamelCase = self.lang_code_to_id[src_lang] _UpperCamelCase = [] _UpperCamelCase = [self.eos_token_id, self.cur_lang_code] def UpperCAmelCase ( self , __a) -> None: '''simple docstring''' _UpperCamelCase = self.lang_code_to_id[lang] _UpperCamelCase = [] _UpperCamelCase = [self.eos_token_id, self.cur_lang_code]
19
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[str] = randn_tensor(A__ , generator=A__ , device=A__ , dtype=A__ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) a__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(A__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase_ (lowercase__ ): snake_case ='ClapFeatureExtractor' snake_case =('RobertaTokenizer', 'RobertaTokenizerFast') def __init__( self , lowercase_ , lowercase_) -> List[str]: super().__init__(lowercase_ , lowercase_) def __call__( self , lowercase_=None , lowercase_=None , lowercase_=None , **lowercase_) -> Optional[Any]: a__ =kwargs.pop('sampling_rate' , lowercase_) if text is None and audios is None: raise ValueError('You have to specify either text or audios. Both cannot be none.') if text is not None: a__ =self.tokenizer(lowercase_ , return_tensors=lowercase_ , **lowercase_) if audios is not None: a__ =self.feature_extractor( lowercase_ , sampling_rate=lowercase_ , return_tensors=lowercase_ , **lowercase_) if text is not None and audios is not None: a__ =audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowercase_) , tensor_type=lowercase_) def __UpperCamelCase ( self , *lowercase_ , **lowercase_) -> Dict: return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def __UpperCamelCase ( self , *lowercase_ , **lowercase_) -> Tuple: return self.tokenizer.decode(*lowercase_ , **lowercase_) @property def __UpperCamelCase ( self) -> Optional[Any]: a__ =self.tokenizer.model_input_names a__ =self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names))
20
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
0
from scipy.stats import spearmanr import datasets UpperCAmelCase_ : Optional[Any] = "\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n" UpperCAmelCase_ : Tuple = "\nArgs:\n predictions (`List[float]`): Predicted labels, as returned by a model.\n references (`List[float]`): Ground truth labels.\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n only the spearmanr score. Defaults to `False`.\nReturns:\n spearmanr (`float`): Spearman correlation coefficient.\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n Example 1:\n >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n >>> print(results)\n {'spearmanr': -0.7}\n\n Example 2:\n >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n ... predictions=[10, 9, 2.5, 6, 4],\n ... return_pvalue=True)\n >>> print(results['spearmanr'])\n -0.7\n >>> print(round(results['spearmanr_pvalue'], 2))\n 0.19\n" UpperCAmelCase_ : List[Any] = R"\\n@book{kokoska2000crc,\n title={CRC standard probability and statistics tables and formulae},\n author={Kokoska, Stephen and Zwillinger, Daniel},\n year={2000},\n publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n author = {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, {\.I}lhan 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, Ant{\^o}nio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\n journal = {Nature Methods},\n year = {2020},\n volume = {17},\n pages = {261--272},\n adsurl = {https://rdcu.be/b08Wh},\n doi = {10.1038/s41592-019-0686-2},\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def A__ ( self :Optional[Any] ): '''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.spearmanr.html"""] , ) def A__ ( self :Union[str, Any] , __snake_case :str , __snake_case :Optional[int] , __snake_case :str=False ): '''simple docstring''' __magic_name__ : Any =spearmanr(__snake_case , __snake_case ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
21
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
0
'''simple docstring''' from jiwer import compute_measures import datasets _snake_case : Dict = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' _snake_case : List[str] = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' _snake_case : List[str] = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class A ( datasets.Metric ): def __lowerCAmelCase ( self : Tuple ) -> Dict: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', ] , ) def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : int=None , lowerCAmelCase_ : Optional[Any]=False ) -> str: """simple docstring""" if concatenate_texts: return compute_measures(lowerCAmelCase_ , lowerCAmelCase_ )["wer"] else: _a = 0 _a = 0 for prediction, reference in zip(lowerCAmelCase_ , lowerCAmelCase_ ): _a = compute_measures(lowerCAmelCase_ , lowerCAmelCase_ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
22
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case__ : Tuple = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : Dict = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys snake_case__ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
23
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : Tuple = logging.get_logger(__name__) UpperCAmelCase_ : Dict = { '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/config.json''', '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/config.json''', '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/config.json''', '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/config.json''', '''roberta-base-openai-detector''': '''https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json''', '''roberta-large-openai-detector''': '''https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json''', } class lowerCAmelCase ( __lowerCAmelCase): __lowercase : Any = '''roberta''' def __init__( self , __SCREAMING_SNAKE_CASE=5_0265 , __SCREAMING_SNAKE_CASE=768 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=3072 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=512 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-12 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE="absolute" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __snake_case = vocab_size __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = hidden_act __snake_case = intermediate_size __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = max_position_embeddings __snake_case = type_vocab_size __snake_case = initializer_range __snake_case = layer_norm_eps __snake_case = position_embedding_type __snake_case = use_cache __snake_case = classifier_dropout class lowerCAmelCase ( __lowerCAmelCase): @property def lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": __snake_case = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __snake_case = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
24
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
0
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeling_tf_common import floats_tensor from .test_framework_agnostic import GenerationIntegrationTestsMixin if is_tf_available(): import tensorflow as tf from transformers import ( AutoTokenizer, TFAutoModelForCausalLM, TFAutoModelForSeqaSeqLM, TFAutoModelForSpeechSeqaSeq, TFAutoModelForVisionaSeq, TFBartForConditionalGeneration, TFLogitsProcessorList, TFMinLengthLogitsProcessor, tf_top_k_top_p_filtering, ) if is_tensorflow_text_available(): import tensorflow_text as text @require_tf class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = tf.convert_to_tensor( [ [ 8.222_0991, # 3rd highest value; idx. 0 -0.562_0044, 5.2322_9752, 4.038_6393, -6.879_8378, -0.5478_5802, -3.201_2153, 2.9277_7176, 1.8817_1953, 7.3534_1276, # 5th highest value; idx. 9 8.4320_7833, # 2nd highest value; idx. 10 -9.8571_1836, -5.9620_9236, -1.1303_9161, -7.111_5294, -0.836_9633, -5.318_6408, 7.0642_7407, 0.8136_9344, -0.8202_3817, -5.917_9796, 0.5881_3443, -6.9977_8438, 4.7155_1189, -0.1877_1637, 7.4402_0759, # 4th highest value; idx. 25 9.3845_0987, # 1st highest value; idx. 26 2.1266_2941, -9.3256_2038, 2.3565_2522, ], # cummulative prob of 5 highest values <= 0.6 [ 0.5842_5518, 4.5313_9238, -5.5751_0464, -6.2803_0699, -7.1952_9503, -4.0212_2551, 1.3933_7037, -6.0670_7057, 1.5948_0517, -9.64_3119, 0.0390_7799, 0.6723_1762, -8.8820_6726, 6.2711_5922, # 4th highest value; idx. 13 2.2852_0723, 4.8276_7506, 4.3042_1368, 8.827_5313, # 2nd highest value; idx. 17 5.4402_9958, # 5th highest value; idx. 18 -4.473_5794, 7.3857_9536, # 3rd highest value; idx. 20 -2.9105_1663, 2.6194_6077, -2.567_4762, -9.4895_9302, -4.0292_2645, -1.3541_6918, 9.6770_2323, # 1st highest value; idx. 27 -5.8947_8553, 1.8537_0467, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above SCREAMING_SNAKE_CASE : List[Any] = tf.convert_to_tensor( [8.22_2099, 7.353_4126, 8.43_2078, 7.440_2075, 9.3_8451, 6.27_1159, 8.82_7531, 5.440_2995, 7.385_7956, 9.67_7023] , dtype=tf.floataa , ) # expected non filtered values as noted above SCREAMING_SNAKE_CASE : Union[str, Any] = tf_top_k_top_p_filtering(a , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 ) SCREAMING_SNAKE_CASE : List[Any] = output[output != -float("inf" )] SCREAMING_SNAKE_CASE : Tuple = tf.cast( tf.where(tf.not_equal(a , tf.constant(-float("inf" ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(a , a , rtol=1e-12 ) tf.debugging.assert_equal(a , a ) @require_tf class _UpperCamelCase ( unittest.TestCase , __A ): '''simple docstring''' if is_tf_available(): lowerCamelCase__ ={ 'AutoModelForCausalLM': TFAutoModelForCausalLM, 'AutoModelForSpeechSeq2Seq': TFAutoModelForSpeechSeqaSeq, 'AutoModelForSeq2SeqLM': TFAutoModelForSeqaSeqLM, 'AutoModelForVision2Seq': TFAutoModelForVisionaSeq, 'LogitsProcessorList': TFLogitsProcessorList, 'MinLengthLogitsProcessor': TFMinLengthLogitsProcessor, 'create_tensor_fn': tf.convert_to_tensor, 'floats_tensor': floats_tensor, 'return_tensors': 'tf', } @slow def __UpperCamelCase ( self : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : str = 2 SCREAMING_SNAKE_CASE : List[str] = 2 class _UpperCamelCase ( tf.Module ): '''simple docstring''' def __init__( self : List[str] , a : Optional[int] ) -> str: """simple docstring""" super(a , self ).__init__() SCREAMING_SNAKE_CASE : Dict = model @tf.function( input_signature=( tf.TensorSpec((None, input_length) , tf.intaa , name="input_ids" ), tf.TensorSpec((None, input_length) , tf.intaa , name="attention_mask" ), ) , jit_compile=a , ) def __UpperCamelCase ( self : Union[str, Any] , a : List[str] , a : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.model.generate( input_ids=a , attention_mask=a , max_new_tokens=a , return_dict_in_generate=a , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : Dict = [[2, 0], [102, 103]] SCREAMING_SNAKE_CASE : Optional[int] = [[1, 0], [1, 1]] SCREAMING_SNAKE_CASE : Any = DummyModel(model=a ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(a , a , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE : Tuple = tf.saved_model.load(a ).signatures["serving_default"] for batch_size in range(1 , len(a ) + 1 ): SCREAMING_SNAKE_CASE : Optional[int] = { "input_ids": tf.constant(dummy_input_ids[:batch_size] ), "attention_mask": tf.constant(dummy_attention_masks[:batch_size] ), } SCREAMING_SNAKE_CASE : Dict = serving_func(**a )["sequences"] SCREAMING_SNAKE_CASE : Union[str, Any] = test_model.generate(**a , max_new_tokens=a ) tf.debugging.assert_equal(a , a ) @slow def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : Union[str, Any] = 2 class _UpperCamelCase ( tf.Module ): '''simple docstring''' def __init__( self : List[str] , a : List[Any] ) -> Optional[int]: """simple docstring""" super(a , self ).__init__() SCREAMING_SNAKE_CASE : List[Any] = model @tf.function( input_signature=( tf.TensorSpec((batch_size, None) , tf.intaa , name="input_ids" ), tf.TensorSpec((batch_size, None) , tf.intaa , name="attention_mask" ), ) , jit_compile=a , ) def __UpperCamelCase ( self : str , a : List[str] , a : str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.model.generate( input_ids=a , attention_mask=a , max_new_tokens=a , return_dict_in_generate=a , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : str = [[2], [102, 103]] SCREAMING_SNAKE_CASE : str = [[1], [1, 1]] SCREAMING_SNAKE_CASE : Optional[Any] = DummyModel(model=a ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(a , a , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE : List[Any] = tf.saved_model.load(a ).signatures["serving_default"] for input_row in range(len(a ) ): SCREAMING_SNAKE_CASE : List[str] = { "input_ids": tf.constant([dummy_input_ids[input_row]] ), "attention_mask": tf.constant([dummy_attention_masks[input_row]] ), } SCREAMING_SNAKE_CASE : Union[str, Any] = serving_func(**a )["sequences"] SCREAMING_SNAKE_CASE : str = test_model.generate(**a , max_new_tokens=a ) tf.debugging.assert_equal(a , a ) @slow @require_tensorflow_text def __UpperCamelCase ( self : Tuple ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: # file needed to load the TF tokenizer hf_hub_download(repo_id="google/flan-t5-small" , filename="spiece.model" , local_dir=a ) class _UpperCamelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : List[str] = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(a , "spiece.model" ) , "rb" ).read() ) SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained("hf-internal-testing/tiny-random-t5" ) def __UpperCamelCase ( self : Union[str, Any] , a : Optional[Any] , *a : Union[str, Any] , **a : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.tokenize(a ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = text.pad_model_inputs( a , max_seq_length=64 , pad_value=self.model.config.pad_token_id ) SCREAMING_SNAKE_CASE : str = self.model.generate(input_ids=a , attention_mask=a ) return self.tokenizer.detokenize(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = CompleteSentenceTransformer() SCREAMING_SNAKE_CASE : Optional[Any] = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name="inputs" ) SCREAMING_SNAKE_CASE : Dict = complete_model(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.keras.Model(a , a ) keras_model.save(a ) def __UpperCamelCase ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = { "do_sample": True, "num_beams": 1, "top_p": 0.7, "top_k": 10, "temperature": 0.7, } SCREAMING_SNAKE_CASE : Dict = 14 SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : int = "Hello, my dog is cute and" SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(a , return_tensors="tf" ) SCREAMING_SNAKE_CASE : str = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : Dict = 638 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = model.generate(**a , eos_token_id=a , **a ) self.assertTrue(expectation == len(generated_tokens[0] ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = [638, 198] with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(**a , eos_token_id=a , **a ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def __UpperCamelCase ( self : Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : Optional[int] = "Hugging Face is a technology company based in New York and Paris." SCREAMING_SNAKE_CASE : List[Any] = bart_tokenizer(a , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : Dict = TFBartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : Dict = bart_model.generate(a ).numpy() class _UpperCamelCase ( __A ): '''simple docstring''' def __UpperCamelCase ( self : Optional[int] , a : int , a : List[str]=None , **a : List[str] ) -> Optional[int]: """simple docstring""" return super().call(a , **a ) SCREAMING_SNAKE_CASE : Optional[int] = FakeBart.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : Union[str, Any] = bart_model.generate(a , foo="bar" ).numpy() self.assertTrue(np.array_equal(a , a ) ) class _UpperCamelCase ( bart_model.model.encoder.__class__ ): '''simple docstring''' def __UpperCamelCase ( self : Tuple , a : Any , **a : List[Any] ) -> Optional[Any]: """simple docstring""" return super().call(a , **a ) SCREAMING_SNAKE_CASE : int = FakeEncoder(bart_model.config , bart_model.model.shared ) SCREAMING_SNAKE_CASE : List[str] = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) SCREAMING_SNAKE_CASE : Union[str, Any] = bart_model.generate(a ).numpy() with self.assertRaises(a ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(a , foo="bar" )
25
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
0
'''simple docstring''' def _a ( _lowerCamelCase = 10 , _lowerCamelCase = 1000 , _lowerCamelCase = True ) -> int: """simple docstring""" assert ( isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("""Invalid value for min_val or max_val (min_value < max_value)""" ) return min_val if option else max_val def _a ( _lowerCamelCase , _lowerCamelCase ) -> int: """simple docstring""" return int((number_a + number_a) / 2 ) def _a ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> None: """simple docstring""" assert ( isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("""argument value for lower and higher must be(lower > higher)""" ) if not lower < to_guess < higher: raise ValueError( """guess value must be within the range of lower and higher value""" ) def answer(_lowerCamelCase ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("""started...""" ) __snake_case : Any = lower __snake_case : List[Any] = higher __snake_case : Tuple = [] while True: __snake_case : List[str] = get_avg(_lowerCamelCase , _lowerCamelCase ) last_numbers.append(_lowerCamelCase ) if answer(_lowerCamelCase ) == "low": __snake_case : Union[str, Any] = number elif answer(_lowerCamelCase ) == "high": __snake_case : Dict = number else: break print(F'''guess the number : {last_numbers[-1]}''' ) print(F'''details : {last_numbers!s}''' ) def _a ( ) -> None: """simple docstring""" __snake_case : List[Any] = int(input("""Enter lower value : """ ).strip() ) __snake_case : Tuple = int(input("""Enter high value : """ ).strip() ) __snake_case : Tuple = int(input("""Enter value to guess : """ ).strip() ) guess_the_number(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": main()
26
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : 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 : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
0
from collections import defaultdict class lowerCamelCase: '''simple docstring''' def __init__( self , snake_case_ , snake_case_ ): _A = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 _A = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(snake_case_ ) ) ] _A = defaultdict(snake_case_ ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 _A = (1 << len(snake_case_ )) - 1 def lowerCAmelCase__ ( self , snake_case_ , snake_case_ ): # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement _A = self.count_ways_until(snake_case_ , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. _A = total_ways_util return self.dp[mask][task_no] def lowerCAmelCase__ ( self , snake_case_ ): # Store the list of persons for each task for i in range(len(snake_case_ ) ): for j in task_performed[i]: self.task[j].append(snake_case_ ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": __A : Optional[int] = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. __A : Any = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
27
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
0
'''simple docstring''' import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A, 'hidden_sizes' ) ) self.parent.assertTrue(hasattr(A, 'num_attention_heads' ) ) class _a : '''simple docstring''' def __init__( self, A, A=13, A=64, A=3, A=3, A=2, A=1, A=16, A=[128, 256, 384], A=[4, 6, 8], A=[2, 3, 4], A=[16, 16, 16], A=0, A=[2, 2, 2], A=[2, 2, 2], A=0.02, A=True, A=True, A=2, ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[int] = image_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE : List[Any] = kernel_size SCREAMING_SNAKE_CASE : Tuple = stride SCREAMING_SNAKE_CASE : Optional[int] = padding SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_sizes SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = depths SCREAMING_SNAKE_CASE : Tuple = key_dim SCREAMING_SNAKE_CASE : List[Any] = drop_path_rate SCREAMING_SNAKE_CASE : Any = patch_size SCREAMING_SNAKE_CASE : Any = attention_ratio SCREAMING_SNAKE_CASE : List[str] = mlp_ratio SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE : str = is_training SCREAMING_SNAKE_CASE : Optional[int] = use_labels SCREAMING_SNAKE_CASE : Optional[Any] = num_labels SCREAMING_SNAKE_CASE : List[Any] = initializer_range def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size], self.num_labels ) SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self ): '''simple docstring''' return LevitConfig( image_size=self.image_size, num_channels=self.num_channels, kernel_size=self.kernel_size, stride=self.stride, padding=self.padding, patch_size=self.patch_size, hidden_sizes=self.hidden_sizes, num_attention_heads=self.num_attention_heads, depths=self.depths, key_dim=self.key_dim, drop_path_rate=self.drop_path_rate, mlp_ratio=self.mlp_ratio, attention_ratio=self.attention_ratio, initializer_range=self.initializer_range, down_ops=self.down_ops, ) def UpperCamelCase_ ( self, A, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = LevitModel(config=A ) model.to(A ) model.eval() SCREAMING_SNAKE_CASE : List[str] = model(A ) SCREAMING_SNAKE_CASE : int = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) SCREAMING_SNAKE_CASE : int = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]), ) def UpperCamelCase_ ( self, A, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Optional[int] = LevitForImageClassification(A ) model.to(A ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(A, labels=A ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' A : Dict = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) A : Optional[int] = ( { '''feature-extraction''': LevitModel, '''image-classification''': (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) A : Optional[Any] = False A : List[Any] = False A : str = False A : Dict = False A : Dict = False def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = LevitModelTester(self ) SCREAMING_SNAKE_CASE : Dict = ConfigTester(self, config_class=A, has_text_modality=A, hidden_size=37 ) def UpperCamelCase_ ( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase_ ( self ): '''simple docstring''' return @unittest.skip(reason='Levit does not use inputs_embeds' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass @unittest.skip(reason='Levit does not support input and output embeddings' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass @unittest.skip(reason='Levit does not output attentions' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(A ) SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Union[str, Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1], A ) def UpperCamelCase_ ( self ): '''simple docstring''' def check_hidden_states_output(A, A, A ): SCREAMING_SNAKE_CASE : Any = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : Tuple = model(**self._prepare_for_class(A, A ) ) SCREAMING_SNAKE_CASE : Optional[int] = outputs.hidden_states SCREAMING_SNAKE_CASE : Dict = len(self.model_tester.depths ) + 1 self.assertEqual(len(A ), A ) SCREAMING_SNAKE_CASE : List[str] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = image_size[0], image_size[1] for _ in range(4 ): SCREAMING_SNAKE_CASE : List[str] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) SCREAMING_SNAKE_CASE : str = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [ height * width, self.model_tester.hidden_sizes[0], ], ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = True check_hidden_states_output(A, A, A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Tuple = True check_hidden_states_output(A, A, A ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass def UpperCamelCase_ ( self, A, A, A=False ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = super()._prepare_for_class(A, A, return_labels=A ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : Dict = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(A ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE : Any = model_class(A ) model.to(A ) model.train() SCREAMING_SNAKE_CASE : Optional[int] = self._prepare_for_class(A, A, return_labels=A ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(**A ).loss loss.backward() def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : Union[str, Any] = True for model_class in self.all_model_classes: if model_class in get_values(A ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(A ) model.gradient_checkpointing_enable() model.to(A ) model.train() SCREAMING_SNAKE_CASE : Tuple = self._prepare_for_class(A, A, return_labels=A ) SCREAMING_SNAKE_CASE : Any = model(**A ).loss loss.backward() def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : Optional[Any] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(A ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F"Testing {model_class} with {problem_type['title']}" ): SCREAMING_SNAKE_CASE : List[str] = problem_type['title'] SCREAMING_SNAKE_CASE : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE : Tuple = model_class(A ) model.to(A ) model.train() SCREAMING_SNAKE_CASE : Tuple = self._prepare_for_class(A, A, return_labels=A ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE : List[Any] = inputs['labels'].unsqueeze(1 ).repeat(1, problem_type['num_labels'] ) SCREAMING_SNAKE_CASE : Optional[int] = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=A ) as warning_list: SCREAMING_SNAKE_CASE : Optional[Any] = model(**A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def UpperCamelCase_ ( self ): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : List[str] = LevitModel.from_pretrained(A ) self.assertIsNotNone(A ) def lowercase__( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class _a ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self ): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( A ) SCREAMING_SNAKE_CASE : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE : str = prepare_img() SCREAMING_SNAKE_CASE : int = image_processor(images=A, return_tensors='pt' ).to(A ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**A ) # verify the logits SCREAMING_SNAKE_CASE : Any = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape, A ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([1.04_48, -0.37_45, -1.83_17] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3], A, atol=1E-4 ) )
28
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __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 a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
0
"""simple docstring""" import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin A_ = 1e-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class __lowerCamelCase : def __init__( self , UpperCAmelCase , UpperCAmelCase=16 , UpperCAmelCase=13 , UpperCAmelCase=7 , UpperCAmelCase=14 , UpperCAmelCase=10 , UpperCAmelCase=19 , UpperCAmelCase=5 , UpperCAmelCase=4 , UpperCAmelCase=True , UpperCAmelCase=16 , UpperCAmelCase=2 , UpperCAmelCase=4 , UpperCAmelCase=4 , UpperCAmelCase="gelu" , UpperCAmelCase=0.1 , UpperCAmelCase=0.1 , UpperCAmelCase=[1, 2, 3, 4, 5] , UpperCAmelCase=25 , UpperCAmelCase=5 , ): lowerCamelCase_ = d_model lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = prediction_length lowerCamelCase_ = context_length lowerCamelCase_ = cardinality lowerCamelCase_ = num_time_features lowerCamelCase_ = lags_sequence lowerCamelCase_ = embedding_dimension lowerCamelCase_ = is_training 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_ = context_length lowerCamelCase_ = prediction_length + label_length lowerCamelCase_ = label_length lowerCamelCase_ = moving_average lowerCamelCase_ = autocorrelation_factor def UpperCAmelCase__ ( self ): return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = config.context_length + max(config.lags_sequence ) lowerCamelCase_ = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) lowerCamelCase_ = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) lowerCamelCase_ = floats_tensor([self.batch_size, _past_length] ) lowerCamelCase_ = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs lowerCamelCase_ = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) lowerCamelCase_ = floats_tensor([self.batch_size, config.prediction_length] ) lowerCamelCase_ = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def UpperCAmelCase__ ( self ): lowerCamelCase_ = self.get_config() lowerCamelCase_ = self.prepare_autoformer_inputs_dict(UpperCAmelCase ) return config, inputs_dict def UpperCAmelCase__ ( self ): lowerCamelCase_ , lowerCamelCase_ = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase ): lowerCamelCase_ = AutoformerModel(config=UpperCAmelCase ).to(UpperCAmelCase ).eval() lowerCamelCase_ = model(**UpperCAmelCase ) lowerCamelCase_ = outputs.encoder_last_hidden_state lowerCamelCase_ = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ = model.get_encoder() encoder.save_pretrained(UpperCAmelCase ) lowerCamelCase_ = AutoformerEncoder.from_pretrained(UpperCAmelCase ).to(UpperCAmelCase ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = model.create_network_inputs(**UpperCAmelCase ) lowerCamelCase_ , lowerCamelCase_ = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) lowerCamelCase_ = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) lowerCamelCase_ = encoder(inputs_embeds=UpperCAmelCase )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) lowerCamelCase_ = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) lowerCamelCase_ = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) lowerCamelCase_ = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) lowerCamelCase_ = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ = model.get_decoder() decoder.save_pretrained(UpperCAmelCase ) lowerCamelCase_ = AutoformerDecoder.from_pretrained(UpperCAmelCase ).to(UpperCAmelCase ) lowerCamelCase_ = decoder( trend=UpperCAmelCase , inputs_embeds=UpperCAmelCase , encoder_hidden_states=UpperCAmelCase , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class __lowerCamelCase ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): a__: Tuple = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () a__: Union[str, Any] = (AutoformerForPrediction,) if is_torch_available() else () a__: List[Any] = {'feature-extraction': AutoformerModel} if is_torch_available() else {} a__: str = False a__: int = False a__: Dict = False a__: List[str] = False a__: Optional[int] = False a__: Optional[Any] = False def UpperCAmelCase__ ( self ): lowerCamelCase_ = AutoformerModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=UpperCAmelCase , has_text_modality=UpperCAmelCase ) def UpperCAmelCase__ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase__ ( self ): lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: lowerCamelCase_ = model_class(UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCAmelCase ) lowerCamelCase_ , lowerCamelCase_ = model_class.from_pretrained(UpperCAmelCase , output_loading_info=UpperCAmelCase ) self.assertEqual(info['''missing_keys'''] , [] ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*UpperCAmelCase ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def UpperCAmelCase__ ( self ): pass def UpperCAmelCase__ ( self ): lowerCamelCase_ = inspect.signature(getattr(UpperCAmelCase , '''forward''' ) ) # The main input is the name of the argument after `self` lowerCamelCase_ = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , UpperCAmelCase ) def UpperCAmelCase__ ( self ): 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.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ = [*signature.parameters.keys()] lowerCamelCase_ = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(UpperCAmelCase )] , UpperCAmelCase ) def UpperCAmelCase__ ( self ): lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ = True lowerCamelCase_ = getattr(self.model_tester , '''seq_length''' , UpperCAmelCase ) lowerCamelCase_ = getattr(self.model_tester , '''decoder_seq_length''' , UpperCAmelCase ) lowerCamelCase_ = getattr(self.model_tester , '''encoder_seq_length''' , UpperCAmelCase ) lowerCamelCase_ = getattr(self.model_tester , '''d_model''' , UpperCAmelCase ) lowerCamelCase_ = getattr(self.model_tester , '''num_attention_heads''' , UpperCAmelCase ) lowerCamelCase_ = d_model // num_attention_heads for model_class in self.all_model_classes: lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = model_class(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCamelCase_ = model(**self._prepare_for_class(UpperCAmelCase , UpperCAmelCase ) ) lowerCamelCase_ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(UpperCAmelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCamelCase_ = True lowerCamelCase_ = model_class(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCamelCase_ = model(**self._prepare_for_class(UpperCAmelCase , UpperCAmelCase ) ) lowerCamelCase_ = outputs.encoder_attentions self.assertEqual(len(UpperCAmelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) lowerCamelCase_ = len(UpperCAmelCase ) lowerCamelCase_ = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(UpperCAmelCase , UpperCAmelCase ) # decoder attentions lowerCamelCase_ = outputs.decoder_attentions self.assertIsInstance(UpperCAmelCase , (list, tuple) ) self.assertEqual(len(UpperCAmelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions lowerCamelCase_ = outputs.cross_attentions self.assertIsInstance(UpperCAmelCase , (list, tuple) ) self.assertEqual(len(UpperCAmelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine lowerCamelCase_ = True lowerCamelCase_ = True lowerCamelCase_ = model_class(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCamelCase_ = model(**self._prepare_for_class(UpperCAmelCase , UpperCAmelCase ) ) self.assertEqual(out_len + 2 , len(UpperCAmelCase ) ) lowerCamelCase_ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(UpperCAmelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def UpperCAmelCase__ ( self ): super().test_retain_grad_hidden_states_attentions() def lowercase ( lowerCAmelCase__="train-batch.pt" ): lowerCamelCase_ = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' ,filename=lowerCAmelCase__ ,repo_type='''dataset''' ) lowerCamelCase_ = torch.load(lowerCAmelCase__ ,map_location=lowerCAmelCase__ ) return batch @require_torch @slow class __lowerCamelCase ( unittest.TestCase ): def UpperCAmelCase__ ( self ): lowerCamelCase_ = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(UpperCAmelCase ) lowerCamelCase_ = prepare_batch() with torch.no_grad(): lowerCamelCase_ = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] lowerCamelCase_ = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , UpperCAmelCase ) lowerCamelCase_ = torch.tensor( [[0.3_5_9_3, -1.3_3_9_8, 0.6_3_3_0], [0.2_2_7_9, 1.5_3_9_6, -0.1_7_9_2], [0.0_4_5_0, 1.3_2_2_5, -0.2_3_3_5]] , device=UpperCAmelCase ) self.assertTrue(torch.allclose(output[0, :3, :3] , UpperCAmelCase , atol=UpperCAmelCase ) ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(UpperCAmelCase ) lowerCamelCase_ = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): lowerCamelCase_ = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state lowerCamelCase_ = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , UpperCAmelCase ) lowerCamelCase_ = torch.tensor( [[-0.0_7_3_4, -0.9_0_3_6, 0.8_3_5_8], [4.7_1_8_6, 2.4_1_1_3, 1.9_5_8_1], [1.7_9_5_3, 2.3_5_5_8, 1.2_9_7_0]] , device=UpperCAmelCase ) self.assertTrue(torch.allclose(output[0, :3, :3] , UpperCAmelCase , atol=UpperCAmelCase ) ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(UpperCAmelCase ) lowerCamelCase_ = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): lowerCamelCase_ = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) lowerCamelCase_ = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , UpperCAmelCase ) lowerCamelCase_ = torch.tensor([3_1_3_0.6_7_6_3, 4_0_5_6.5_2_9_3, 7_0_5_3.0_7_8_6] , device=UpperCAmelCase ) lowerCamelCase_ = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , UpperCAmelCase , rtol=1e-1 ) )
29
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
0
from __future__ import annotations import collections import pprint from pathlib import Path def lowerCamelCase__ ( _lowercase ): '''simple docstring''' return "".join(sorted(_lowercase ) ) def lowerCamelCase__ ( _lowercase ): '''simple docstring''' return word_by_signature[signature(_lowercase )] __a = Path(__file__).parent.joinpath('words.txt').read_text(encoding='utf-8') __a = sorted({word.strip().lower() for word in data.splitlines()}) __a = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": __a = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('anagrams.txt', 'w') as file: file.write('all_anagrams = \n ') file.write(pprint.pformat(all_anagrams))
30
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
0
import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class lowerCamelCase_ : '''simple docstring''' def __init__( self : Any , _lowerCAmelCase : Optional[int]=2 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : Tuple=64 , _lowerCAmelCase : List[str]=None ): SCREAMING_SNAKE_CASE_ = np.random.default_rng(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = length SCREAMING_SNAKE_CASE_ = rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self : Optional[int] ): return self.length def __getitem__( self : str , _lowerCAmelCase : Union[str, Any] ): return {"x": self.x[i], "y": self.y[i]} class lowerCamelCase_ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Tuple , _lowerCAmelCase : Dict=0 , _lowerCAmelCase : List[str]=0 , _lowerCAmelCase : str=False ): super().__init__() SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE_ = True def lowerCAmelCase_ ( self : Dict , _lowerCAmelCase : Union[str, Any]=None ): if self.first_batch: print(F"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}" ) SCREAMING_SNAKE_CASE_ = False return x * self.a[0] + self.b[0] class lowerCamelCase_ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , _lowerCAmelCase : Any=0 , _lowerCAmelCase : Any=0 , _lowerCAmelCase : Optional[Any]=False ): super().__init__() SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor(_lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor(_lowerCAmelCase ).float() ) SCREAMING_SNAKE_CASE_ = True def lowerCAmelCase_ ( self : Optional[Any] , _lowerCAmelCase : Optional[int]=None ): if self.first_batch: print(F"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}" ) SCREAMING_SNAKE_CASE_ = False return x * self.a + self.b def UpperCAmelCase_ ( __UpperCAmelCase : Dict , __UpperCAmelCase : int = 16 ) -> Union[str, Any]: from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE_ = {'train': 'tests/test_samples/MRPC/train.csv', 'validation': 'tests/test_samples/MRPC/dev.csv'} SCREAMING_SNAKE_CASE_ = load_dataset('csv' , data_files=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = datasets['train'].unique('label' ) SCREAMING_SNAKE_CASE_ = {v: i for i, v in enumerate(__UpperCAmelCase )} def tokenize_function(__UpperCAmelCase : Optional[int] ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ = tokenizer( examples['sentence1'] , examples['sentence2'] , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' ) if "label" in examples: SCREAMING_SNAKE_CASE_ = [label_to_id[l] for l in examples['label']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_ = datasets.map( __UpperCAmelCase , batched=__UpperCAmelCase , remove_columns=['sentence1', 'sentence2', 'label'] , ) def collate_fn(__UpperCAmelCase : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__UpperCAmelCase , padding='max_length' , max_length=1_28 , return_tensors='pt' ) return tokenizer.pad(__UpperCAmelCase , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ = DataLoader(tokenized_datasets['train'] , shuffle=__UpperCAmelCase , collate_fn=__UpperCAmelCase , batch_size=2 ) SCREAMING_SNAKE_CASE_ = DataLoader(tokenized_datasets['validation'] , shuffle=__UpperCAmelCase , collate_fn=__UpperCAmelCase , batch_size=1 ) return train_dataloader, eval_dataloader
31
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ = { "configuration_table_transformer": [ "TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TableTransformerConfig", "TableTransformerOnnxConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TableTransformerForObjectDetection", "TableTransformerModel", "TableTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
32
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
0
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class __magic_name__ (snake_case_ ,snake_case_ ,snake_case_ ,unittest.TestCase ): '''simple docstring''' __lowercase : List[str] = StableUnCLIPPipeline __lowercase : Any = TEXT_TO_IMAGE_PARAMS __lowercase : List[str] = TEXT_TO_IMAGE_BATCH_PARAMS __lowercase : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS __lowercase : Any = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false __lowercase : List[Any] = False def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ): snake_case__ = 32 snake_case__ = embedder_hidden_size # prior components torch.manual_seed(0 ) snake_case__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) snake_case__ = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_a , projection_dim=_a , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) snake_case__ = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=_a , num_layers=1 , ) torch.manual_seed(0 ) snake_case__ = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=10_00 , clip_sample=_a , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) snake_case__ = StableUnCLIPImageNormalizer(embedding_dim=_a ) snake_case__ = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) snake_case__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) snake_case__ = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_a , 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=10_00 , ) ) torch.manual_seed(0 ) snake_case__ = 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=_a , layers_per_block=1 , upcast_attention=_a , use_linear_projection=_a , ) torch.manual_seed(0 ) snake_case__ = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.00085 , beta_end=0.012 , prediction_type='''v_prediction''' , set_alpha_to_one=_a , steps_offset=1 , ) torch.manual_seed(0 ) snake_case__ = AutoencoderKL() snake_case__ = { # prior components '''prior_tokenizer''': prior_tokenizer, '''prior_text_encoder''': prior_text_encoder, '''prior''': prior, '''prior_scheduler''': prior_scheduler, # image noising components '''image_normalizer''': image_normalizer, '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder, '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, } return components def SCREAMING_SNAKE_CASE__ ( self:Dict , _a:Tuple , _a:Any=0 ): if str(_a ).startswith('''mps''' ): snake_case__ = torch.manual_seed(_a ) else: snake_case__ = torch.Generator(device=_a ).manual_seed(_a ) snake_case__ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''prior_num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE__ ( self:Optional[Any] ): snake_case__ = torch_device == '''cpu''' self._test_attention_slicing_forward_pass(test_max_difference=_a ) def SCREAMING_SNAKE_CASE__ ( self:Tuple ): snake_case__ = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=_a ) @slow @require_torch_gpu class __magic_name__ (unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self:str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self:Union[str, Any] ): snake_case__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) snake_case__ = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) # 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() snake_case__ = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case__ = pipe('''anime turle''' , generator=_a , output_type='''np''' ) snake_case__ = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(_a , _a ) def SCREAMING_SNAKE_CASE__ ( self:Dict ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() snake_case__ = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) snake_case__ = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() snake_case__ = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) snake_case__ = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
33
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
0
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu SCREAMING_SNAKE_CASE_ = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def __snake_case ( _lowercase ,_lowercase=None ,_lowercase=None ,_lowercase=None ): """simple docstring""" UpperCamelCase = True while ask_again: UpperCamelCase = input(_lowercase ) try: if default is not None and len(_lowercase ) == 0: return default return convert_value(_lowercase ) if convert_value is not None else result except Exception: if error_message is not None: print(_lowercase ) def __snake_case ( _lowercase ,_lowercase=[] ,_lowercase=None ,_lowercase=0 ): """simple docstring""" UpperCamelCase = BulletMenu(_lowercase ,_lowercase ) UpperCamelCase = menu.run(default_choice=_lowercase ) return convert_value(_lowercase ) if convert_value is not None else result def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = int(_lowercase ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = int(_lowercase ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = int(_lowercase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = int(_lowercase ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = int(_lowercase ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def __snake_case ( _lowercase ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class snake_case_ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) -> Any: UpperCamelCase = super()._format_usage(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) UpperCamelCase = usage.replace('''<command> [<args>] ''' , '''''') return usage
34
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
0
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def a ( A__ ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [ '''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(A__ , A__ ) def a ( A__ ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = emb.weight.shape SCREAMING_SNAKE_CASE__ : List[Any] = nn.Linear(A__ , A__ , bias=A__ ) SCREAMING_SNAKE_CASE__ : Tuple = emb.weight.data return lin_layer def a ( A__ ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = torch.load(A__ , map_location='''cpu''' ) SCREAMING_SNAKE_CASE__ : Tuple = mam_aaa['''args'''] or mam_aaa['''cfg''']['''model'''] SCREAMING_SNAKE_CASE__ : Any = mam_aaa['''model'''] remove_ignore_keys_(A__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict['''encoder.embed_tokens.weight'''].shape[0] SCREAMING_SNAKE_CASE__ : Any = MaMaaaConfig( vocab_size=A__ , max_position_embeddings=1_0_2_4 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='''relu''' , ) SCREAMING_SNAKE_CASE__ : List[str] = state_dict['''decoder.embed_tokens.weight'''] SCREAMING_SNAKE_CASE__ : Dict = MaMaaaForConditionalGeneration(A__ ) model.model.load_state_dict(A__ , strict=A__ ) SCREAMING_SNAKE_CASE__ : int = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": a_ :Any = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ :Any = parser.parse_args() a_ :int = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
35
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = 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 flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Tuple = [ '''GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GraphormerForGraphClassification''', '''GraphormerModel''', '''GraphormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys __lowercase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
36
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class A__ : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase__ : List[str] , lowerCamelCase__ : str=13 , lowerCamelCase__ : Optional[Any]=2 , lowerCamelCase__ : Any=24 , lowerCamelCase__ : Optional[Any]=16 , lowerCamelCase__ : int=True , lowerCamelCase__ : List[str]=True , lowerCamelCase__ : List[Any]=32 , lowerCamelCase__ : List[str]=5 , lowerCamelCase__ : Dict=4 , lowerCamelCase__ : Optional[Any]=37 , lowerCamelCase__ : Any="gelu" , lowerCamelCase__ : Union[str, Any]=0.1 , lowerCamelCase__ : Optional[int]=0.1 , lowerCamelCase__ : str=10 , lowerCamelCase__ : Optional[Any]=0.02 , lowerCamelCase__ : str=None , lowerCamelCase__ : List[str]=2 , lowerCamelCase__ : Optional[Any]=2 , ): a__ : str = parent a__ : Any = batch_size a__ : Dict = patch_size a__ : List[Any] = max_length a__ : str = num_mel_bins a__ : Optional[Any] = is_training a__ : Optional[int] = use_labels a__ : List[Any] = hidden_size a__ : str = num_hidden_layers a__ : Any = num_attention_heads a__ : Union[str, Any] = intermediate_size a__ : List[str] = hidden_act a__ : str = hidden_dropout_prob a__ : Tuple = attention_probs_dropout_prob a__ : List[Any] = type_sequence_label_size a__ : Any = initializer_range a__ : str = scope a__ : List[str] = frequency_stride a__ : Union[str, Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) a__ : List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 a__ : List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 a__ : Tuple = frequency_out_dimension * time_out_dimension a__ : List[str] = num_patches + 2 def _UpperCamelCase( self : List[str] ): a__ : Any = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) a__ : List[Any] = None if self.use_labels: a__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : List[str] = self.get_config() return config, input_values, labels def _UpperCamelCase( self : Optional[int] ): return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , 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=lowerCamelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : Tuple , lowerCamelCase__ : int , lowerCamelCase__ : Optional[int] ): a__ : List[Any] = ASTModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() a__ : Dict = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase( self : str ): a__ : Dict = self.prepare_config_and_inputs() ( ( a__ ), ( a__ ), ( a__ ), ) : Optional[int] = config_and_inputs a__ : List[Any] = {"input_values": input_values} return config, inputs_dict @require_torch class A__ ( A__ , A__ , unittest.TestCase ): """simple docstring""" _lowercase = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) _lowercase = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) _lowercase = False _lowercase = False _lowercase = False _lowercase = False def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : int , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Dict ): if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def _UpperCamelCase( self : str ): a__ : str = ASTModelTester(self ) a__ : Any = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=37 ) def _UpperCamelCase( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason="AST does not use inputs_embeds" ) def _UpperCamelCase( self : List[str] ): pass def _UpperCamelCase( self : Optional[int] ): a__, a__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Any = model_class(lowerCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase__ , nn.Linear ) ) def _UpperCamelCase( self : Tuple ): a__, a__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Dict = model_class(lowerCamelCase__ ) a__ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Optional[int] = [*signature.parameters.keys()] a__ : Optional[Any] = ["input_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] ): a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) @slow def _UpperCamelCase( self : int ): for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Union[str, Any] = ASTModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def UpperCamelCase_ ( ) -> Any: a__ : Optional[int] = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" ) a__, a__ : List[str] = torchaudio.load(__a ) return audio, sampling_rate @require_torch @require_torchaudio class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase( self : List[str] ): return ( ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ) if is_torchaudio_available() else None ) @slow def _UpperCamelCase( self : Optional[int] ): a__ : int = self.default_feature_extractor a__ : Optional[Any] = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(lowerCamelCase__ ) a__ : Any = self.default_feature_extractor a__, a__ : Dict = prepare_audio() a__ : str = audio.squeeze().numpy() a__ : Any = feature_extractor(lowerCamelCase__ , sampling_rate=lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): a__ : Any = model(**lowerCamelCase__ ) # verify the logits a__ : Union[str, Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) a__ : List[str] = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase__ , atol=1E-4 ) )
37
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
0
'''simple docstring''' from __future__ import annotations A_ : Tuple = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = graph # mapping node to its parent in resulting breadth first tree snake_case__ : dict[str, str | None] = {} snake_case__ : Dict = source_vertex def __UpperCamelCase ( self ): snake_case__ : Optional[int] = {self.source_vertex} snake_case__ : int = None snake_case__ : Any = [self.source_vertex] # first in first out queue while queue: snake_case__ : List[Any] = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = vertex queue.append(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): if target_vertex == self.source_vertex: return self.source_vertex snake_case__ : Union[str, Any] = self.parent.get(__SCREAMING_SNAKE_CASE ) if target_vertex_parent is None: snake_case__ : Optional[Any] = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__SCREAMING_SNAKE_CASE ) return self.shortest_path(__SCREAMING_SNAKE_CASE ) + f"->{target_vertex}" if __name__ == "__main__": A_ : Optional[int] = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
38
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = "sew-d" def __init__( self : Dict , _UpperCamelCase : Union[str, Any]=3_2 , _UpperCamelCase : Dict=7_6_8 , _UpperCamelCase : Optional[Any]=1_2 , _UpperCamelCase : int=1_2 , _UpperCamelCase : Tuple=3_0_7_2 , _UpperCamelCase : Optional[int]=2 , _UpperCamelCase : int=5_1_2 , _UpperCamelCase : Any=2_5_6 , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True , _UpperCamelCase : Optional[int]=("p2c", "c2p") , _UpperCamelCase : Any="layer_norm" , _UpperCamelCase : str="gelu_python" , _UpperCamelCase : Optional[int]=0.1 , _UpperCamelCase : Any=0.1 , _UpperCamelCase : Dict=0.1 , _UpperCamelCase : Optional[Any]=0.0 , _UpperCamelCase : int=0.1 , _UpperCamelCase : Dict=0.02 , _UpperCamelCase : List[str]=1e-7 , _UpperCamelCase : Dict=1e-5 , _UpperCamelCase : str="group" , _UpperCamelCase : Optional[Any]="gelu" , _UpperCamelCase : List[str]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _UpperCamelCase : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _UpperCamelCase : Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _UpperCamelCase : Tuple=False , _UpperCamelCase : Optional[Any]=1_2_8 , _UpperCamelCase : List[str]=1_6 , _UpperCamelCase : Any=True , _UpperCamelCase : Union[str, Any]=0.05 , _UpperCamelCase : List[str]=1_0 , _UpperCamelCase : List[Any]=2 , _UpperCamelCase : int=0.0 , _UpperCamelCase : Dict=1_0 , _UpperCamelCase : List[str]=0 , _UpperCamelCase : str="mean" , _UpperCamelCase : Dict=False , _UpperCamelCase : List[str]=False , _UpperCamelCase : Optional[Any]=2_5_6 , _UpperCamelCase : Tuple=0 , _UpperCamelCase : Optional[Any]=1 , _UpperCamelCase : Tuple=2 , **_UpperCamelCase : Any , ) ->Tuple: super().__init__(**_UpperCamelCase , pad_token_id=_UpperCamelCase , bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase ) snake_case_ = hidden_size snake_case_ = feat_extract_norm snake_case_ = feat_extract_activation snake_case_ = list(_UpperCamelCase ) snake_case_ = list(_UpperCamelCase ) snake_case_ = list(_UpperCamelCase ) snake_case_ = conv_bias snake_case_ = num_conv_pos_embeddings snake_case_ = num_conv_pos_embedding_groups snake_case_ = len(self.conv_dim ) snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = squeeze_factor snake_case_ = max_position_embeddings snake_case_ = position_buckets snake_case_ = share_att_key snake_case_ = relative_attention snake_case_ = norm_rel_ebd snake_case_ = list(_UpperCamelCase ) snake_case_ = hidden_act snake_case_ = num_attention_heads snake_case_ = hidden_dropout snake_case_ = attention_dropout snake_case_ = activation_dropout snake_case_ = feat_proj_dropout snake_case_ = final_dropout snake_case_ = layer_norm_eps snake_case_ = feature_layer_norm_eps snake_case_ = initializer_range snake_case_ = 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 snake_case_ = apply_spec_augment snake_case_ = mask_time_prob snake_case_ = mask_time_length snake_case_ = mask_time_min_masks snake_case_ = mask_feature_prob snake_case_ = mask_feature_length snake_case_ = mask_feature_min_masks # ctc loss snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # sequence classification snake_case_ = use_weighted_layer_sum snake_case_ = classifier_proj_size @property def snake_case__( self : Dict ) ->Optional[Any]: return functools.reduce(operator.mul , self.conv_stride , 1 )
39
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
0
def UpperCamelCase ( snake_case__ : list[int] , snake_case__ : list[int] ) -> None: UpperCamelCase : int = len(snake_case__ ) print('The following activities are selected:' ) # The first activity is always selected UpperCamelCase : List[Any] = 0 print(snake_case__ , end=',' ) # Consider rest of the activities for j in range(snake_case__ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(snake_case__ , end=',' ) UpperCamelCase : Tuple = j if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = [1, 3, 0, 5, 8, 5] __UpperCAmelCase = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
40
'''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 __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = 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] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
0
'''simple docstring''' import numpy as np import qiskit def _A ( A__ = 8 , A__ = None ): """simple docstring""" __lowercase = np.random.default_rng(seed=A__ ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. __lowercase = 6 * key_len # Measurement basis for Alice's qubits. __lowercase = rng.integers(2 , size=A__ ) # The set of states Alice will prepare. __lowercase = rng.integers(2 , size=A__ ) # Measurement basis for Bob's qubits. __lowercase = rng.integers(2 , size=A__ ) # Quantum Circuit to simulate BB84 __lowercase = qiskit.QuantumCircuit(A__ , name='''BB84''' ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(A__ ): if alice_state[index] == 1: bbaa_circ.x(A__ ) if alice_basis[index] == 1: bbaa_circ.h(A__ ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(A__ ): if bob_basis[index] == 1: bbaa_circ.h(A__ ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. __lowercase = qiskit.Aer.get_backend('''aer_simulator''' ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. __lowercase = qiskit.execute(A__ , A__ , shots=1 , seed_simulator=A__ ) # Returns the result of measurement. __lowercase = job.result().get_counts(A__ ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. __lowercase = ''''''.join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( A__ , A__ , A__ ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. __lowercase = gen_key[:key_len] if len(A__ ) >= key_len else gen_key.ljust(A__ , '''0''' ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
41
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[str] = randn_tensor(A__ , generator=A__ , device=A__ , dtype=A__ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) a__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(A__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
0
'''simple docstring''' import os import string import sys A_ = 1 << 8 A_ = { "tab": ord("\t"), "newline": ord("\r"), "esc": 27, "up": 65 + ARROW_KEY_FLAG, "down": 66 + ARROW_KEY_FLAG, "right": 67 + ARROW_KEY_FLAG, "left": 68 + ARROW_KEY_FLAG, "mod_int": 91, "undefined": sys.maxsize, "interrupt": 3, "insert": 50, "delete": 51, "pg_up": 53, "pg_down": 54, } A_ = KEYMAP["up"] A_ = KEYMAP["left"] if sys.platform == "win32": A_ = [] A_ = { B"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG, B"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG, B"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG, B"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG, B"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG, B"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG, B"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG, B"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG, } for i in range(10): A_ = ord(str(i)) def _UpperCamelCase ( ) -> int: if os.name == "nt": import msvcrt lowerCamelCase_ = 'mbcs' # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(__UpperCamelCase ) == 0: # Read the keystroke lowerCamelCase_ = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): lowerCamelCase_ = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: lowerCamelCase_ = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP['mod_int'] ) ) WIN_CH_BUFFER.append(__UpperCamelCase ) if ord(__UpperCamelCase ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) lowerCamelCase_ = chr(KEYMAP['esc'] ) except KeyError: lowerCamelCase_ = cha[1] else: lowerCamelCase_ = ch.decode(__UpperCamelCase ) else: lowerCamelCase_ = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty lowerCamelCase_ = sys.stdin.fileno() lowerCamelCase_ = termios.tcgetattr(__UpperCamelCase ) try: tty.setraw(__UpperCamelCase ) lowerCamelCase_ = sys.stdin.read(1 ) finally: termios.tcsetattr(__UpperCamelCase ,termios.TCSADRAIN ,__UpperCamelCase ) return ch def _UpperCamelCase ( ) -> str: lowerCamelCase_ = get_raw_chars() if ord(__UpperCamelCase ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(__UpperCamelCase ) == KEYMAP["esc"]: lowerCamelCase_ = get_raw_chars() if ord(__UpperCamelCase ) == KEYMAP["mod_int"]: lowerCamelCase_ = get_raw_chars() if ord(__UpperCamelCase ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(__UpperCamelCase ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(__UpperCamelCase ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
42
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
0
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class _a ( UpperCamelCase__ ): def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: float ) -> float: """simple docstring""" return 0.0 def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) lowercase__ = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = 5_12 lowercase__ = [1] + [0] * (size - 1) lowercase__ = [filter_type.process(SCREAMING_SNAKE_CASE ) for item in inputs] lowercase__ = [0] * (samplerate - size) # zero-padding outputs += filler lowercase__ = np.abs(np.fft.fft(SCREAMING_SNAKE_CASE ) ) lowercase__ = 20 * np.logaa(SCREAMING_SNAKE_CASE ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('''Frequency (Hz)''' ) plt.xscale('''log''' ) # Display within reasonable bounds lowercase__ = get_bounds(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('''Gain (dB)''' ) plt.plot(SCREAMING_SNAKE_CASE ) plt.show() def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = 5_12 lowercase__ = [1] + [0] * (size - 1) lowercase__ = [filter_type.process(SCREAMING_SNAKE_CASE ) for item in inputs] lowercase__ = [0] * (samplerate - size) # zero-padding outputs += filler lowercase__ = np.angle(np.fft.fft(SCREAMING_SNAKE_CASE ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('''Frequency (Hz)''' ) plt.xscale('''log''' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('''Phase shift (Radians)''' ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE , -2 * pi ) ) plt.show()
43
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) UpperCAmelCase_ : Optional[int] = { 'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'], 'processing_trocr': ['TrOCRProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ 'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrOCRForCausalLM', 'TrOCRPreTrainedModel', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys UpperCAmelCase_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
0
UpperCamelCase = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", "\"": ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on UpperCamelCase = {value: key for key, value in MORSE_CODE_DICT.items()} def A ( lowercase__ : str ) -> str: return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def A ( lowercase__ : str ) -> str: return "".join(REVERSE_DICT[char] for char in message.split() ) def A ( ) -> None: UpperCamelCase__ :Union[str, Any] = """Morse code here!""" print(lowercase__ ) UpperCamelCase__ :Dict = encrypt(lowercase__ ) print(lowercase__ ) UpperCamelCase__ :Optional[Any] = decrypt(lowercase__ ) print(lowercase__ ) if __name__ == "__main__": main()
45
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
0
"""simple docstring""" import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> List[str]: '''simple docstring''' _lowerCamelCase : int = LxmertConfig.from_json_file(_lowerCamelCase ) print(F"""Building PyTorch model from configuration: {config}""" ) _lowerCamelCase : int = LxmertForPreTraining(_lowerCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _lowerCamelCase ) if __name__ == "__main__": _lowerCAmelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCAmelCase : List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
46
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
0
import math from numpy import inf from scipy.integrate import quad def UpperCAmelCase__ ( lowerCamelCase_ : float ): if num <= 0: raise ValueError('math domain error' ) return quad(lowerCamelCase_ , 0 , lowerCamelCase_ , args=(lowerCamelCase_) )[0] def UpperCAmelCase__ ( lowerCamelCase_ : float , lowerCamelCase_ : float ): return math.pow(lowerCamelCase_ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
47
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : Optional[Any] = { "configuration_git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitVisionConfig"], "processing_git": ["GitProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = [ "GIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GitForCausalLM", "GitModel", "GitPreTrainedModel", "GitVisionModel", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : 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 : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
0
"""simple docstring""" def lowercase__ ( snake_case_ :int , snake_case_ :int ): return base * power(snake_case_ , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('Raise base to the power of exponent using recursion...') _lowercase : Dict = int(input('Enter the base: ').strip()) _lowercase : Optional[Any] = int(input('Enter the exponent: ').strip()) _lowercase : List[str] = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents _lowercase : List[str] = 1 / result print(f"""{base} to the power of {exponent} is {result}""")
49
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase : Any = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : Union[str, Any] = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : Tuple = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : str = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys UpperCamelCase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
50
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __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 a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
0
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Tuple , a__ : List[Any]=None , a__ : str=None , **a__ : Tuple ): UpperCAmelCase = 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__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = 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 : Optional[Any] , a__ : Optional[int]=None , a__ : List[str]=None , a__ : int=None , **a__ : Tuple ): if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = 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 : List[str] , *a__ : Union[str, Any] , **a__ : Optional[int] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : int , *a__ : Optional[int] , **a__ : int ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : str ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __snake_case ( self : Optional[int] ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a__ , ) return self.image_processor_class @property def __snake_case ( self : List[Any] ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a__ , ) return self.image_processor
51
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
0
"""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 A = '''bart''' A = True @st.cache(allow_output_mutation=a_) def __A ( ) -> Dict: if LOAD_DENSE_INDEX: __a : Optional[Any] = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''') __a : Dict = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''').to('''cuda:0''') __a : Union[str, Any] = qar_model.eval() else: __a , __a : Optional[int] = (None, None) if MODEL_TYPE == "bart": __a : List[Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''') __a : Tuple = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''').to('''cuda:0''') __a : Optional[int] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''') sas_model.load_state_dict(save_dict['''model''']) __a : List[Any] = sas_model.eval() else: __a , __a : List[str] = 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=a_) def __A ( ) -> Optional[Any]: if LOAD_DENSE_INDEX: __a : str = faiss.StandardGpuResources() __a : Tuple = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''')['''train'''] __a : Dict = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , ) __a : Dict = faiss.IndexFlatIP(1_28) __a : Optional[int] = faiss.index_cpu_to_gpu(a_ , 1 , a_) wikiaab_gpu_index_flat.add(a_) # TODO fix for larger GPU else: __a , __a : List[str] = (None, None) __a : int = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}]) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a_) def __A ( ) -> Union[str, Any]: __a : Union[str, Any] = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''') __a : List[str] = elia['''train_eli5'''] __a : Tuple = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28)) __a : Any = faiss.IndexFlatIP(1_28) eli5_train_q_index.add(a_) return (elia_train, eli5_train_q_index) A , A , A = load_indexes() A , A , A , A = load_models() A , A = load_train_data() def __A ( a_ :str , a_ :str=10) -> Dict: __a : List[Any] = embed_questions_for_retrieval([question] , a_ , a_) __a , __a : Tuple = eli5_train_q_index.search(a_ , a_) __a : Union[str, Any] = [elia_train[int(a_)] for i in I[0]] return nn_examples def __A ( a_ :List[Any] , a_ :int="wiki40b" , a_ :Any="dense" , a_ :Dict=10) -> Any: if source == "none": __a , __a : Any = (''' <P> '''.join(['''''' for _ in range(11)]).strip(), []) else: if method == "dense": __a , __a : Optional[Any] = query_qa_dense_index( a_ , a_ , a_ , a_ , a_ , a_) else: __a , __a : int = query_es_index( a_ , a_ , index_name='''english_wiki40b_snippets_100w''' , n_results=a_ , ) __a : Any = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] __a : Any = '''question: {} context: {}'''.format(a_ , a_) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a_: None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a_: None), }) def __A ( a_ :Tuple , a_ :Any , a_ :Tuple , a_ :List[Any]=64 , a_ :int=2_56 , a_ :Any=False , a_ :Dict=2 , a_ :Dict=0.9_5 , a_ :List[Any]=0.8) -> List[Any]: with torch.no_grad(): __a : str = qa_sas_generate( a_ , a_ , a_ , num_answers=1 , num_beams=a_ , min_len=a_ , max_len=a_ , do_sample=a_ , temp=a_ , top_p=a_ , top_k=a_ , max_input_length=10_24 , device='''cuda:0''' , )[0] return (answer, support_list) st.title('''Long Form Question Answering with ELI5''') # Start sidebar A = '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>''' A = ''' <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 A = ''' 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) A = [ '''Answer the question''', '''View the retrieved document only''', '''View the most similar ELI5 question and answer''', '''Show me everything, please!''', ] A = st.sidebar.checkbox('''Demo options''') if demo_options: A = st.sidebar.selectbox( '''''', action_list, index=3, ) A = action_list.index(action_st) A = st.sidebar.selectbox( '''''', ['''Show full text of passages''', '''Show passage section titles'''], index=0, ) A = show_type == '''Show full text of passages''' else: A = 3 A = True A = st.sidebar.checkbox('''Retrieval options''') if retrieval_options: A = ''' ### 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) A = st.sidebar.selectbox('''Which Wikipedia format should the model use?''', ['''wiki40b''', '''none''']) A = st.sidebar.selectbox('''Which Wikipedia indexer should the model use?''', ['''dense''', '''sparse''', '''mixed''']) else: A = '''wiki40b''' A = '''dense''' A = '''beam''' A = 2 A = 64 A = 256 A = None A = None A = st.sidebar.checkbox('''Generation options''') if generate_options: A = ''' ### 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) A = st.sidebar.selectbox('''Would you like to use beam search or sample an answer?''', ['''beam''', '''sampled''']) A = st.sidebar.slider( '''Minimum generation length''', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) A = st.sidebar.slider( '''Maximum generation length''', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": A = st.sidebar.slider('''Beam size''', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: A = st.sidebar.slider( '''Nucleus sampling p''', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) A = st.sidebar.slider( '''Temperature''', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) A = None # start main text A = [ '''<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?''', ] A = 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>": A = st.text_input('''Enter your question here:''', '''''') else: A = question_s if st.button('''Show me!'''): if action in [0, 1, 3]: if index_type == "mixed": A , A = make_support(question, source=wiki_source, method='''dense''', n_results=10) A , A = make_support(question, source=wiki_source, method='''sparse''', n_results=10) A = [] 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)] A = support_list[:10] A = '''<P> ''' + ''' <P> '''.join([res[-1] for res in support_list]) else: A , A = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: A , A = 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): A = '''https://en.wikipedia.org/wiki/{}'''.format(res[0].replace(''' ''', '''_''')) A = res[1].strip() if sec_titles == "": A = '''[{}]({})'''.format(res[0], wiki_url) else: A = sec_titles.split(''' & ''') A = ''' & '''.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]: A = find_nearest_training(question) A = nn_train_list[0] st.markdown( '''--- \n ### The most similar question in the ELI5 training set was: \n\n {}'''.format(train_exple['''title''']) ) A = [ '''{}. {}'''.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))) A = ''' --- **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)
52
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : Optional[Any] = logging.get_logger(__name__) _snake_case : Dict = { 'google/vivit-b-16x2-kinetics400': ( 'https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" a_ = """vivit""" def __init__( self : Union[str, Any] , lowerCAmelCase_ : int=2_2_4 , lowerCAmelCase_ : Optional[int]=3_2 , lowerCAmelCase_ : Dict=[2, 1_6, 1_6] , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : Union[str, Any]=7_6_8 , lowerCAmelCase_ : str=1_2 , lowerCAmelCase_ : Dict=1_2 , lowerCAmelCase_ : int=3_0_7_2 , lowerCAmelCase_ : Dict="gelu_fast" , lowerCAmelCase_ : List[Any]=0.0 , lowerCAmelCase_ : int=0.0 , lowerCAmelCase_ : Optional[int]=0.02 , lowerCAmelCase_ : int=1e-06 , lowerCAmelCase_ : Optional[int]=True , **lowerCAmelCase_ : Any , ) -> str: __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 = initializer_range __lowerCAmelCase = layer_norm_eps __lowerCAmelCase = image_size __lowerCAmelCase = num_frames __lowerCAmelCase = tubelet_size __lowerCAmelCase = num_channels __lowerCAmelCase = qkv_bias super().__init__(**lowerCAmelCase_ )
53
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
0
import collections import os import re from pathlib import Path __lowercase : Tuple ="""src/transformers""" # Matches is_xxx_available() __lowercase : Union[str, Any] =re.compile(R"""is\_([a-z_]*)_available()""") # Catches a one-line _import_struct = {xxx} __lowercase : List[str] =re.compile(R"""^_import_structure\s+=\s+\{([^\}]+)\}""") # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __lowercase : Optional[int] =re.compile(R"""\s+\"\S*\":\s+\[([^\]]*)\]""") # Catches a line if not is_foo_available __lowercase : Any =re.compile(R"""^\s*if\s+not\s+is\_[a-z_]*\_available\(\)""") # Catches a line _import_struct["bla"].append("foo") __lowercase : Optional[Any] =re.compile(R"""^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)""") # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __lowercase : Optional[int] =re.compile(R"""^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]""") # Catches a line with an object between quotes and a comma: "MyModel", __lowercase : List[Any] =re.compile(R"""^\s+\"([^\"]+)\",""") # Catches a line with objects between brackets only: ["foo", "bar"], __lowercase : Optional[int] =re.compile(R"""^\s+\[([^\]]+)\]""") # Catches a line with from foo import bar, bla, boo __lowercase : Union[str, Any] =re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") # Catches a line with try: __lowercase : Optional[int] =re.compile(R"""^\s*try:""") # Catches a line with else: __lowercase : Union[str, Any] =re.compile(R"""^\s*else:""") def a__ ( lowercase__ ): '''simple docstring''' if _re_test_backend.search(lowercase__ ) is None: return None UpperCAmelCase_ =[b[0] for b in _re_backend.findall(lowercase__ )] backends.sort() return "_and_".join(lowercase__ ) def a__ ( lowercase__ ): '''simple docstring''' with open(lowercase__ , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCAmelCase_ =f.readlines() UpperCAmelCase_ =0 while line_index < len(lowercase__ ) and not lines[line_index].startswith("_import_structure = {" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase__ ): return None # First grab the objects without a specific backend in _import_structure UpperCAmelCase_ =[] while not lines[line_index].startswith("if TYPE_CHECKING" ) and find_backend(lines[line_index] ) is None: UpperCAmelCase_ =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase__ ): UpperCAmelCase_ =_re_one_line_import_struct.search(lowercase__ ).groups()[0] UpperCAmelCase_ =re.findall(R"\[([^\]]+)\]" , lowercase__ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", " )] ) line_index += 1 continue UpperCAmelCase_ =_re_import_struct_key_value.search(lowercase__ ) if single_line_import_search is not None: UpperCAmelCase_ =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(", " ) if len(lowercase__ ) > 0] objects.extend(lowercase__ ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) line_index += 1 UpperCAmelCase_ ={"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING" ): # If the line is an if not is_backend_available, we grab all objects associated. UpperCAmelCase_ =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCAmelCase_ =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCAmelCase_ =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 4 ): UpperCAmelCase_ =lines[line_index] if _re_import_struct_add_one.search(lowercase__ ) is not None: objects.append(_re_import_struct_add_one.search(lowercase__ ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase__ ) is not None: UpperCAmelCase_ =_re_import_struct_add_many.search(lowercase__ ).groups()[0].split(", " ) UpperCAmelCase_ =[obj[1:-1] for obj in imports if len(lowercase__ ) > 0] objects.extend(lowercase__ ) elif _re_between_brackets.search(lowercase__ ) is not None: UpperCAmelCase_ =_re_between_brackets.search(lowercase__ ).groups()[0].split(", " ) UpperCAmelCase_ =[obj[1:-1] for obj in imports if len(lowercase__ ) > 0] objects.extend(lowercase__ ) elif _re_quote_object.search(lowercase__ ) is not None: objects.append(_re_quote_object.search(lowercase__ ).groups()[0] ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) elif line.startswith(" " * 1_2 + "\"" ): objects.append(line[1_3:-3] ) line_index += 1 UpperCAmelCase_ =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend UpperCAmelCase_ =[] while ( line_index < len(lowercase__ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("else" ) ): UpperCAmelCase_ =lines[line_index] UpperCAmelCase_ =_re_import.search(lowercase__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 UpperCAmelCase_ ={"none": objects} # Let's continue with backend-specific objects while line_index < len(lowercase__ ): # If the line is an if is_backend_available, we grab all objects associated. UpperCAmelCase_ =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCAmelCase_ =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCAmelCase_ =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 8 ): UpperCAmelCase_ =lines[line_index] UpperCAmelCase_ =_re_import.search(lowercase__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 1_2 ): objects.append(line[1_2:-2] ) line_index += 1 UpperCAmelCase_ =objects else: line_index += 1 return import_dict_objects, type_hint_objects def a__ ( lowercase__ , lowercase__ ): '''simple docstring''' def find_duplicates(lowercase__ ): return [k for k, v in collections.Counter(lowercase__ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] UpperCAmelCase_ =[] for key in import_dict_objects.keys(): UpperCAmelCase_ =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) UpperCAmelCase_ =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): UpperCAmelCase_ ="base imports" if key == "none" else F'{key} backend' errors.append(F'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F' {a} in _import_structure but not in TYPE_HINT.' ) return errors def a__ ( ): '''simple docstring''' UpperCAmelCase_ =[] for root, _, files in os.walk(lowercase__ ): if "__init__.py" in files: UpperCAmelCase_ =os.path.join(lowercase__ , "__init__.py" ) UpperCAmelCase_ =parse_init(lowercase__ ) if objects is not None: UpperCAmelCase_ =analyze_results(*lowercase__ ) if len(lowercase__ ) > 0: UpperCAmelCase_ =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append("\n".join(lowercase__ ) ) if len(lowercase__ ) > 0: raise ValueError("\n\n".join(lowercase__ ) ) def a__ ( ): '''simple docstring''' UpperCAmelCase_ =[] for path, directories, files in os.walk(lowercase__ ): for folder in directories: # Ignore private modules if folder.startswith("_" ): directories.remove(lowercase__ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase__ ) / folder).glob("*.py" ) ) ) == 0: continue UpperCAmelCase_ =str((Path(lowercase__ ) / folder).relative_to(lowercase__ ) ) UpperCAmelCase_ =short_path.replace(os.path.sep , "." ) submodules.append(lowercase__ ) for fname in files: if fname == "__init__.py": continue UpperCAmelCase_ =str((Path(lowercase__ ) / fname).relative_to(lowercase__ ) ) UpperCAmelCase_ =short_path.replace(".py" , "" ).replace(os.path.sep , "." ) if len(submodule.split("." ) ) == 1: submodules.append(lowercase__ ) return submodules __lowercase : Optional[Any] =[ """convert_pytorch_checkpoint_to_tf2""", """modeling_flax_pytorch_utils""", """models.esm.openfold_utils""", ] def a__ ( ): '''simple docstring''' from transformers.utils import direct_transformers_import UpperCAmelCase_ =direct_transformers_import(lowercase__ ) UpperCAmelCase_ =set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(lowercase__ , "__init__.py" ) , "r" ) as f: UpperCAmelCase_ =f.read() import_structure_keys.update(set(re.findall(R"import_structure\[\"([^\"]*)\"\]" , lowercase__ ) ) ) UpperCAmelCase_ =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(lowercase__ ) > 0: UpperCAmelCase_ ="\n".join(F'- {module}' for module in module_not_registered ) raise ValueError( "The following submodules are not properly registed in the main init of Transformers:\n" F'{list_of_modules}\n' "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." ) if __name__ == "__main__": check_all_inits() check_submodules()
54
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE :Tuple = { 'configuration_bert': ['BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BertConfig', 'BertOnnxConfig'], 'tokenization_bert': ['BasicTokenizer', 'BertTokenizer', 'WordpieceTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :str = ['BertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BertForMaskedLM', 'BertForMultipleChoice', 'BertForNextSentencePrediction', 'BertForPreTraining', 'BertForQuestionAnswering', 'BertForSequenceClassification', 'BertForTokenClassification', 'BertLayer', 'BertLMHeadModel', 'BertModel', 'BertPreTrainedModel', 'load_tf_weights_in_bert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Tuple = [ 'TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFBertEmbeddings', 'TFBertForMaskedLM', 'TFBertForMultipleChoice', 'TFBertForNextSentencePrediction', 'TFBertForPreTraining', 'TFBertForQuestionAnswering', 'TFBertForSequenceClassification', 'TFBertForTokenClassification', 'TFBertLMHeadModel', 'TFBertMainLayer', 'TFBertModel', 'TFBertPreTrainedModel', ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = ['TFBertTokenizer'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Optional[int] = [ 'FlaxBertForCausalLM', 'FlaxBertForMaskedLM', 'FlaxBertForMultipleChoice', 'FlaxBertForNextSentencePrediction', 'FlaxBertForPreTraining', 'FlaxBertForQuestionAnswering', 'FlaxBertForSequenceClassification', 'FlaxBertForTokenClassification', 'FlaxBertModel', 'FlaxBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
0
'''simple docstring''' from __future__ import annotations def _a (lowercase__ : int , lowercase__ : int ) -> tuple[int, int]: """simple docstring""" if b == 0: return (1, 0) ((__snake_case) , (__snake_case)) = extended_euclid(lowercase__ , a % b ) __snake_case = a // b return (y, x - k * y) def _a (lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int ) -> int: """simple docstring""" ((__snake_case) , (__snake_case)) = extended_euclid(lowercase__ , lowercase__ ) __snake_case = na * na __snake_case = ra * x * na + ra * y * na return (n % m + m) % m def _a (lowercase__ : int , lowercase__ : int ) -> int: """simple docstring""" ((__snake_case) , (__snake_case)) = extended_euclid(lowercase__ , lowercase__ ) if b < 0: __snake_case = (b % n + n) % n return b def _a (lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int ) -> int: """simple docstring""" __snake_case , __snake_case = invert_modulo(lowercase__ , lowercase__ ), invert_modulo(lowercase__ , lowercase__ ) __snake_case = na * na __snake_case = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
56
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
0
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : List[str] = logging.get_logger(__name__) A_ : Optional[int] = { 'google/vivit-b-16x2-kinetics400': ( 'https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Any ='''vivit''' def __init__( self , _lowerCamelCase=2_2_4 , _lowerCamelCase=3_2 , _lowerCamelCase=[2, 1_6, 1_6] , _lowerCamelCase=3 , _lowerCamelCase=7_6_8 , _lowerCamelCase=1_2 , _lowerCamelCase=1_2 , _lowerCamelCase=3_0_7_2 , _lowerCamelCase="gelu_fast" , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-06 , _lowerCamelCase=True , **_lowerCamelCase , ): UpperCamelCase_: Optional[Any] = hidden_size UpperCamelCase_: Dict = num_hidden_layers UpperCamelCase_: Any = num_attention_heads UpperCamelCase_: Optional[Any] = intermediate_size UpperCamelCase_: List[Any] = hidden_act UpperCamelCase_: List[str] = hidden_dropout_prob UpperCamelCase_: Optional[Any] = attention_probs_dropout_prob UpperCamelCase_: Dict = initializer_range UpperCamelCase_: Tuple = layer_norm_eps UpperCamelCase_: List[str] = image_size UpperCamelCase_: Tuple = num_frames UpperCamelCase_: str = tubelet_size UpperCamelCase_: str = num_channels UpperCamelCase_: List[str] = qkv_bias super().__init__(**_lowerCamelCase )
57
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = 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 flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
0
"""simple docstring""" import datasets from .evaluate import evaluate __lowerCAmelCase : Tuple = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' __lowerCAmelCase : Union[str, Any] = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' __lowerCAmelCase : Optional[Any] = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): """simple docstring""" def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": { """id""": datasets.Value("""string""" ), """prediction_text""": datasets.features.Sequence(datasets.Value("""string""" ) ), }, """references""": { """id""": datasets.Value("""string""" ), """answers""": datasets.features.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), }, } ) , codebase_urls=["""https://www.atticusprojectai.org/cuad"""] , reference_urls=["""https://www.atticusprojectai.org/cuad"""] , ) def UpperCAmelCase__ ( self , _lowercase , _lowercase ) -> Optional[int]: '''simple docstring''' snake_case_ : Union[str, Any] = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions} snake_case_ : Union[str, Any] = [ { """paragraphs""": [ { """qas""": [ { """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]], """id""": ref["""id"""], } for ref in references ] } ] } ] snake_case_ : int = evaluate(dataset=_lowercase , predictions=_lowercase ) return score
58
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
0
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __A = { "susnato/ernie-m-base_pytorch": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json", "susnato/ernie-m-large_pytorch": "https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json", } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "ernie_m" lowercase_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__(self : Any , UpperCAmelCase_ : int = 250_002 , UpperCAmelCase_ : int = 768 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : int = 3_072 , UpperCAmelCase_ : str = "gelu" , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : int = 514 , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : float = 1E-0_5 , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[Any]=0.0 , **UpperCAmelCase_ : str , ) ->List[str]: '''simple docstring''' super().__init__(pad_token_id=UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: List[Any] =vocab_size lowerCamelCase__: Tuple =hidden_size lowerCamelCase__: Optional[Any] =num_hidden_layers lowerCamelCase__: Optional[Any] =num_attention_heads lowerCamelCase__: List[str] =intermediate_size lowerCamelCase__: Optional[int] =hidden_act lowerCamelCase__: Optional[Any] =hidden_dropout_prob lowerCamelCase__: Union[str, Any] =attention_probs_dropout_prob lowerCamelCase__: Optional[Any] =max_position_embeddings lowerCamelCase__: Union[str, Any] =initializer_range lowerCamelCase__: Dict =layer_norm_eps lowerCamelCase__: List[str] =classifier_dropout lowerCamelCase__: Union[str, Any] =is_decoder lowerCamelCase__: str =act_dropout
59
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
0